text:
Generate valid Fibonacci tilings
Background
The Fibonacci tiling is a tiling of the (1D) line using two segments: a short one, S, and a long one, L (their length ratio is the golden ratio, but that's not relevant to this challenge). For a tiling using these two prototiles to actually be a Fibonacci tiling, the following conditions have to be fulfilled:

The tiling must not contain the subsequence SS.
The tiling must not contain the subsequence LLL.
If a new tiling is composed by performing all of the following substitutions, the result must still be a Fibonacci tiling:

LL → S
S → L
L → (empty string)

Let's look at some examples:
SLLSLLSLLSLS

This looks like a valid tiling, because it doesn't contain two *S*s or three *L*s but let's perform the composition:
LSLSLSLL

That still looks fine, but if we compose this again, we get
LLLS

which is not a valid Fibonacci tiling. Therefore, the two previous sequences weren't valid tilings either.
On the other hand, if we start with
LSLLSLSLLSLSLL

and repeatedly compose this to shorter sequences
LSLLSLLS
LSLSL
LL
S

all results are valid Fibonacci tilings, because we never obtain SS or LLL anywhere inside those strings.
For further reading, there is a thesis which uses this tiling as a simple 1D analogy to Penrose tilings.
The Challenge
Write a program or function which, given a non-negative integer N, returns all valid Fibonacci tiling in the form of strings containing N characters (being S or L).
You may take input via function argument, STDIN or ARGV and return or print the result.
This is code golf, the shortest answer (in bytes) wins.
Examples
N      Output
0      (an empty string)
1      S, L
2      SL, LS, LL
3      LSL, SLS, LLS, SLL
4      SLSL, SLLS, LSLS, LSLL, LLSL
5      LLSLL, LLSLS, LSLLS, LSLSL, SLLSL, SLSLL
...
8      LLSLLSLS, LLSLSLLS, LSLLSLLS, LSLLSLSL, LSLSLLSL, SLLSLLSL, SLLSLSLL, SLSLLSLL, SLSLLSLS

Should that be LSLSL -> LL ?

@tolos Ah yes, good catch. I fixed that. FYI, this happened because I actually generated the string the other way round, starting from the bottom using similar decomposition rules, and those aren't exactly reversible when it comes to the boundaries of the fragment.

Is there any limit on the input N? like what is the max that N can be?

CJam, 70 62 59 bytes
Qali{_'L:Xf+\'S:Yf++}*{{_X2*/Xf-Yf/Xf*Y*}h]N*_X3*#\Y2*#=},p

Reads from STDIN. Try it online.
Example run
$ cjam tilings.cjam <<< 5
["LLSLL" "SLSLL" "SLLSL" "LSLSL" "LSLLS" "LLSLS"]

How it works
The idea is to push all strings of L's and S's of the proper length, successively apply the transformation to each until the result is an empty string, concatenate the sequences of strings and search for the forbidden substrings.
Qa         " Push R := [ '' ].                                                            ";
li{        " Do the following int(input()) times:                                         ";
  _'L:Xf+  " Append (X := 'L') to a copy of all strings in R.                             ";
  \'S:Yf+  " Append (Y := 'S') to all original strings in R.                              ";
  +        " Concatenate the arrays into R.                                               ";
}*         " R now contains all strings of L's and S's of length int(input()).            ";
{          " For each S ∊ R:                                                              ";
  {        "                                                                              ";
    _      " Push a copy of S.                                                            ";
    X2*/   " Split S at 'LL'.                                                             ";
    Xf-    " Remove 'L' from the chunks.                                                  ";
    Yf/    " Split the chunks at 'S'.                                                     ";
    Xf*    " Join the chunks, separating by 'L'.                                          ";
    Y*     " Join, separating by 'S'.                                                     ";
  }h       " If the resulting string is non-empty, repeat.                                ";
  ]N*      " Join the array of resulting strings from S to '', separating by linefeeds.   ";
  _X3*#    " Push the index of 'LLL' a copy in the resulting string (-1 if not present).  ";
  \Y2*#    " Push the index of 'SS' in the original string (-1 if not present).           ";
  =        " Check if the indexes are equal; this happens if and only if both are -1.     ";
},         " Filter: Keep S in R if and only if = pushed 1.                               ";
p          " Print a string representation of R.                                          ";

APL (Dyalog Unicode), 43 bytes
(1+∘÷⍣=1){'LS'[∪2</⍺|(⍺×(⍳÷⊢)2*⍵)∘.+⍳⍵]}1∘+

Try it online!
This uses the alternative formulation (actually the first one) shown in the linked paper: the closest integer staircase to the line \$y = x/\phi\$, where \$\phi\$ is the golden ratio \$\frac{\sqrt5+1}{2}\$.
Given the initial vertical offset from the line \$h\$ (which can be positive or negative), the next term (one of LS) can be determined by the following rule:

If \$h<0\$ (below the line), \$h←h+1\$ and emit S.
Otherwise (over the line), \$h←h-(\phi-1)\$ and emit L.

Since \$h-(\phi-1) = h+1-\phi\$, we can always increment and take modulo \$\phi\$ of it. Then the condition \$h<0\$ changes to \$h<\phi-1\$, but it doesn't affect the resulting sequence of terms.
Then the problem becomes to sample enough values for initial \$h\$ so that we can get all possible sequences of SL for any given length \$n\$. I choose \$2^{n+1}\$ points uniformly spaced over the interval \$[0,\phi)\$, which works for small \$n\$, and the gap size reduces faster than that induced by the collection of lines \$y=x/\phi+c\$, each passing through some lattice point inside \$0 \le x \le n\$.
Finally, I determine the actual SL terms by checking each consecutive pair: S if left < right, L otherwise, and take unique sequences.
(1+∘÷⍣=1){'LS'[∪2</⍺|(⍺×(⍳÷⊢)2*⍵)∘.+⍳⍵]}1∘+  ⍝ Input: n
(1+∘÷⍣=1){...}1∘+  ⍝ Pass n+1 and phi to the inner dfn...
⍳⍵            ⍝ Range 0..n
∘.+           ⍝ Outer product by addition...
(⍺×(⍳÷⊢)2*⍵)  ⍝ 2^(n+1) uniformly separated numbers in [0,phi)
⍺|            ⍝ Modulo phi
2</           ⍝ Pairwise comparison in row direction
              ⍝ (1 if right is higher, 0 otherwise)
∪             ⍝ Take unique rows
'LS'[...]     ⍝ Map 0, 1 to L, S

GolfScript (86 bytes)
~:|'LS'1/\{{.{1&!'LLS'2/=}%'SS'/'SLS'*[.(1&{'LS'\+}*]{.)1&{'SL'+}*}/}%.&}*['']+{,|=},p

This is an inflationary approach: it starts with L and S and expands them using the rules LL -> SLS, L -> S, S -> LL, and leading or trailing S can have an L added at the word boundary.
Online demo

@MartinBüttner, I normally would link to an online demo with golfscript.apphb.com, but it's running an old version with a bug around nested loops (fixed in the Dec 3, 2012 release) and can't correctly execute this program.

@MartinBüttner Oops. Thanks guys for letting me know about the bug. I updated the website with the new GS version. Click this link for the demo.

@w0lf, thanks for the update (and for the recent change to increase the time limit too).

Brachylog, 69 bytes
~{Ėl|l.&ċ∈ᵛ"LS"&~c=ᵐ{¬{s₂tʰhᵗ=}&}cᵐ{"LL"∧"S"|"S"∧"L"|"L"∧""}ᵐcẹ↰∧}ᵘcᵐ

Try it online!
How it works
First define a predicate, that has a valid fibonacci tiling as input (as a list of "L" and "S"), and its length as output.
Ėl|

It's either an empty list Ė, returning it's length l or …
l.&ċ∈ᵛ"LS"

Something which length is the output and is a list which elements all are elements of "LS". (This part was rather annoying for how simple it should be; I couldn't generate strings up to length N consisting of "LS".)
&~c=ᵐ

Also, the input splitted in groups where each group has only one unique element, e.g. [S, LL, S] or [S, L, L, S] or [LLLL] …
{¬{s₂tʰhᵗ=}&}

Has no two consecutive groups where the first group's last element and the second group's first element are the same – to filter out [S, L, L, S]. (Is there a way to drop {…&} here?)
cᵐ{"LL"∧"S"|"S"∧"L"|"L"∧""}ᵐcẹ↰∧

Those groups are then replaced. If a group doesn't match one of the three rules, the whole partition of the string gets thrown out, i.e. [LLLL] isn't valid. The replaced groups then, converted to a list, must also fulfill this predicate.
~{…}ᵘcᵐ

We now find all unique fibonacci tilings that have the length of the input and convert the lists back to strings.

Haskell, 217
import Control.Monad
data F=L|S deriving (Eq)
f n=filter s$replicateM n [L,S]
r (L:L:m)=S:r m
r (S:m)=L:r m
r (L:m)=r m
r []=[]
s []=True
s m|v m=s$r m
s _=False
v (L:L:L:_)=False
v (S:S:_)=False
v (_:m)=v m
v []=True

Explaination:
I define 4 functions:

f takes an integer and returns the result
replicateM n [L,S] creates all possible permutations of [L,S] with the length n
filter s ... will filter this list (of lists) with the function s
r reduces a a given list by 1 level.
This is simply done by pattern matching. A list starting with 2 L will become a list starting with S and the reduced remaining
v validates a given list by the rules given (no 3 continuous L, no 2 continous S)
if the list starts with one of the 2 illegal sequences (L,L,L or S,S) the result is False, an empty list is valid, and an non-empty list is checked again with the first element removed
s checks if a list and all reduced lists are valid.
Again: an empty list is valid (and can't be reduced further).
If the list given as argument is valid then the list is reduced ad checked with s again.
Otherwise the result is False


text:
Can you connect the dots?
This challenge is based off of Flow Free.  An online version can be found here: http://www.moh97.us/
You will be given a puzzle, and you must return 1 if the puzzle is solvable, or 0 if it is not.
To solve a puzzle, the player must create a path to connect each pair of numbers using every empty square exactly once.
You are passed in the dimensions of the square, and then the x,y,c (where c is a number representing the color) of each dot.  For example:
If 5,5 0,0,0 3,0,1 1,1,2 1,2,2 4,2,1 4,4,0 was passed to you, it would represent:
0..1.
.2...
.2..1
....0

And should return 1.

Here are some more test problems:
5,2 2,0,1 0,1,2 4,1,2 represents:
..1..
2...2

and is not solvable because there is only 1 1.
4,2 0,0,0 3,0,0 0,1,0 3,1,0 represents:
0..0
0..0

and is not solvable because it includes more than 2 0s.
8,6 0,0,1 7,5,1 represents:
1.......
........
........
........
........
.......1

and is not solvable (as you can't use every square).
2,5 0,0,1 2,0,6 4,0,6 0,1,4 3,1,4 4,1,1 represents:
1.6.6
4..41

and is not solvable because you cannot connect the 1s.
6,3 1,0,4 5,0,1 0,1,4 1,1,3 5,1,3 0,2,2 3,2,2 5,2,1 represents:
.4...1
43...3
2..2.1

and is not solvable because you cannot connect the 1s (or the 3s), as the two paths must necessarily cross.
5,2 0,0,1 3,0,1 0,1,3 4,1,1 represents:
1..1.
3...3

and is not solvable because you cannot use all of the squares in building a path.
2,2 0,0,0 1,1,0 represents:
1.
.1

and is not solvable because you can't use all of the squares here either
Here are some more tests:
5,5 0,3,0 0,4,1 1,2,2 1,3,1 2,0,0 3,0,4 3,1,2 3,3,5 3,4,4 4,4,5 should return 1
13,13 1,1,0 9,1,1 10,1,2 11,1,3 1,2,4 2,2,5 5,2,6 7,2,7 3,3,0 5,4,6 6,4,1 9,6,3 4,7,8 5,8,9 12,8,8 11,9,10 2,10,4 4,10,2 9,10,5 11,10,7 1,11,9 12,12,10 should return 1
7,7 0,0,0 0,1,1 1,1,2 2,1,3 4,2,4 0,3,1 5,3,3 0,4,4 2,4,5 5,4,2 0,5,0 1,5,5 3,5,6 3,7,6 should return 0

This is a code golf, and the standard rules apply.

Any style of IO & args acceptable?  e.g. function vs program, return value vs stdout, etc.

@DarrenStone yes.

Does a solution have to be "realistically" correct or just theoretically correct? For instance, the state space can be broken down into assigning one of 6 possible input-to-input configurations to each empty cell. Solvability is easily determined by attempting all 6^N combinations and returning 1 if any one of them visits all cells and connects all terminals. Obviously this approach wouldn't complete in a reasonable amount of time for anything but the smallest N (number of empty cells), but we still have a mathematical guarantee that the algorithm would eventually return the correct value.

I would expect the algorithm to solve the 13x13 board I gave in under a minute.  If brute force works, then go ahead.

@NathanMerrill: In that case, you may have some kind of NP hardness combined with state explosion working against you here. For the case of a 13x13 grid with 1's in opposing corners, the number of potential solutions is astronomical. A general solver realistically couldn't rely on brute force of any kind. Barring that as an option, the only solutions I can envision would be topological in nature and would require small libraries worth of code to implement.

Perhaps if you came up with two huge sets of playing grids (one public for testing, one private for validation) using a common algorithm and deemed the winner to be the submission that correctly identified the solvability of the most grids in the private set in some reasonable amount of time per grid, with program size as a tiebreaker if two submissions had equal utility. I'd definitely try my hand at that.

@COTO I do not think this is a NP hard problem.  A person would easily be able to determine if it is solvable or not.  A correct puzzle is possible to solve logically.

@NathanMerrill: The problem is reducible to SAT and thus NP hard.

@NathanMerrill reducing a problem to SAT means that the problem is in NP, not that it is NP-hard -- it's reducing SAT to a problem that shows NP-hardness of the problem.  The page you linked to does have a link to a proof of NP-completeness though.

Is 13,13 1,1,0 9,1,1 10,1,2 11,1,3 1,2,4 2,2,5 5,2,6 7,2,7 3,3,0 5,4,6 6,4,1 9,6,3 4,7,8 5,8,9 12,8,8 11,9,10 2,10,4 4,10,2 9,10,5 11,10,7 1,11,9 12,12,10 actually a valid input? You refer to "digit color"s, but 10 is not a digit - is this a mistake, or else what are the constraints on c?

@VisualMelon Digit color is the wrong word.  Each color is represented by a different number, not digit.

Can we assume that color "numbers" are non-negative and have some upper bound?

They are non-negative, and assume that they are in the integer range for your language.

Haskell
import Data.List.Split
import qualified Data.Sequence as Q
import Data.List
import Control.Monad

data A a = S a | E a | P a | X deriving Eq

sc = foldr1 (Q.><)
sp b x y p = Q.update y (Q.update x p $ b `Q.index` y) b
dt b c | S c `elem` sc b = E c
       | otherwise = S c
ad b [x, y, c] = sp b x y (dt b c)

ep b [x, y, c] = do
  let nps = filter ob [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]
      ns = map gp nps
  [b | E c `elem` ns] ++ do
    (x', y') <- filter ((== X) . gp) nps
    ep (sp b x' y' (P c)) [x', y', c]
  where ob (u, v) = 0 <= u && u < length (b `Q.index` 0) && 0 <= v && v < length b
        gp (u, v) = b `Q.index` v `Q.index` u

rd i = let [c, r] : ps = (map read . splitOn ",") <$> words i :: [[Int]]
           e = Q.replicate r $ Q.replicate c X
           cs = map last ps
           ss = nubBy (\[_,_,c1] [_,_,c2] -> c1 == c2) ps
           b = foldl ad e ps
           bs = foldM ep b ss
       in if even (length cs) && length ss == length cs `div` 2 &&
             (all (\[j,k] -> j==k) . chunksOf 2 . sort $ cs) &&
             any (null . Q.elemIndicesL X . sc) bs
           then 1
           else 0

main = rd <$> getContents >>= print

Key

sc: Seq concat
sp: set position
dt: dot type (ie, start or end of line)
ad: add dot
ep: extend path
rd: run dots (primary pure algorithm)

Thanks for the submission, and welcome to PPCG stack exchange. This is a code golf challenge, meaning the purpose is to write the shortest program which solves the challenge. You're in the lead, because you have the only answer, but you should try to shorten your program as much as possible.

I'm honestly impressed that you answered this question after all this time. Also, this problem was more of a code-challenge, but I used code-golf, as it was hard to come up with a different scoring basis.

Yes, I didn't worry too much about the "golf" aspect; I'm trying to learn Haskell and it seemed like a fun problem :-)

Python3, 538 bytes:
R=range
def f(x,y,v):
 d={}
 for j in R(x):
  for k in R(y):d[r]=d.get(r:=v.get((j,k),-1),[])+[(j,k)]
 if any(i!=-1 and len(d[i])!=2 for i in d):return 0
 D=eval(str(d));del D[(M:=max(d))][0]
 q=[(M,D,d[M][0],0)]
 while q:
  M,D,(j,k),C=q.pop(0)
  if(j,k)in D[M]:
   Y=eval(str(D));del Y[M]
   if(M:=max(Y))!=-1:q+=[(M,Y,Y[M][0],0)];del Y[M][0]
   if{-1:[]}==Y:return 1
   continue
  for J,K in[(-1,0),(1,0),(0,1),(0,-1)]:
   if(T:=(j+J,k+K))in D[-1]:Y=eval(str(D));Y[-1].remove(T);q+=[(M,Y,T,C+1)]
   elif T in D[M]and C:q+=[(M,D,T,C+1)]

Try it online!

Btw, you can ident your code with a tab instead of 4 spaces. Its also 1 byte and more readable than indenting with 1 space

When there is a number and a letter after like 1 and and you can write 1and.
In this case: -1and, 2for,

@TKirishima There is actually one exception, which is 0or - it gets confused with an octal literal. (10or works fine though.)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

authors: شركة إمكان للتمويل

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
multiplication table in javascript
This javascript code:
for(x=1;x<6;x++)for(y=1;y<6;y++)console.log((y==1?'\n':'')+x+'*'+y+'='+x*y);
prints the following:
1*1=1
1*2=2
1*3=3
1*4=4
1*5=5

2*1=2
2*2=4
2*3=6
2*4=8
2*5=10

3*1=3
3*2=6
3*3=9
3*4=12
3*5=15

4*1=4
4*2=8
4*3=12
4*4=16
4*5=20

5*1=5
5*2=10
5*3=15
5*4=20
5*5=25

2 questions:

Is there a smaller (in bytes) way to do the same?
What is the smallest code that can do the same without using 2 for statements?

Before the downvotes and close votes come in: this is on-topic

@MartinBüttner which doesn't change the fact that this is technically a language-specific challenge ;-)

Why are there two blocks of 1s, two blocks of 3s, and no block of 2s or 4s? I don't think that's what the code outputs...

At least in firebug console, the part (y==1?'\n':'') has no effect (no blank lines to separate runs).

@edc65 That is because both Chrome and Firebug print the actual value instead of the string representation as Firefox does.

@jan Dvorak: you are right. There is a bug with my code.

I hope you actually require multiplication tables of 1 through 5 instead of what your example output says ...

@Optimizer: Yes, thanks. It was a bad initial paste. Fixed.

Single for loop, 80 75 72 68 bytes
I will try to make the code smaller too, but as far as single for loop goes:
for(i=5;i<30;)console.log(k=i/5|0,"*",l=i%5+1,"=",k*l,++i%5?"":"\n")

Try it in your console! (Although IE gives the best results)

Don't forget to include the code length in the header

"Is there a smaller (in bytes) way to do the same?" -- so, it surely is code-golf

Should I add it?

There. It's tagged code-golf now.

Try in your MSIE console! In chrome and firefox and firebug the output is very different... (no problem for me, just to make it clear)

Yeah, There is a discussion going wrt Fx Devtools to remove the quotes, then it will be equivalent to MSIE. Chrome and Firebug are both buggy though ...

Assigning and printing the result (k=i/5|0) is a neat trick. Thanks.

@cherouvim - Yeah, there are many other tricks that you can find at http://codegolf.stackexchange.com/questions/37624/tips-for-golfing-in-ecmascript-6/ and http://codegolf.stackexchange.com/questions/2682/tips-for-golfing-in-javascript

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Tangent Polygon Extensions
Draw something that looks like this:

In more precise terms, draw a circle of radius r, with n evenly-spaces tangent lines of length l. Connect the ends of these lines to form a new n-sided regular polygon.
Rules
r = circle radius
n = number of tangent lines - must be evenly spaced around circle (n>=3)
l = side length of tangent lines
Create a program that accepts the arguments { r, n, l } and draws the required output.
Units are in pixels.
There is no restrictions to the location of the drawing, as long as all of it is visible.
The picture is pretty self-explanatory.
This is code-golf, so shortest code in bytes wins!

I assume n will be >= 3, is there a maximum?  Do you want the tangents and circle as well?

Yes, n>=3, (intersection in ok if l is not long enough). You should draw the circle and tangents. I think the maximum is basically when the output is a shaded circle. In other words, the maximum is the realistic maximum for a drawing like this.

Do the pixel units even apply if we produce a vector graphic? Because in such a case pixels are actually quite ill-defined. Or do we have to produce rasterised graphics?

@MartinBüttner, you may ignore the pixel unit with your (fancy) vector graphics if there is some sort of scale (like an axis).

Mathematica, 135 132 131 123 bytes
{r,n,l}=Input[];Graphics[{{0,0}~Circle~r,Line[Join@@Array[{b=(a=r{c=Cos[t=2Pi#/n],s=Sin@t})-l{s,-c},a,b}&,n+1]]},Axes->1>0]

This code expects the input (via a prompt) exactly as specified in the question: e.g. {100, 6, 150}. It produces a vector graphic, so I'm including an axis, as specified in the comments by the OP.
Both the tangents and the polygon are actually a single line strip, by traversing "polygon-corner, tangent point, polygon-corner, next polygon-corner, tangent point, polygon-corner..."

If it wasn't for the axis, I could even do this in 107 bytes:
{r,n,l}=Input[];Graphics@{Circle[],Line[Join@@Array[{b=(a={c=Cos[t=2Pi#/n],s=Sin@t})-l/r{s,-c},a,b}&,n+1]]}

Additional savings (apart from Axes->1>0) come from the fact that I can now rescale everything by r, which simplifies the call to Circle yielding a unit circle.

{0,0}~Circle~r

@DavidCarraher heh, I had actually already done that in the 135 bytes, but forgot to copy it back into my notebook, so it got reverted when I made the Unicode change. thanks!

Python, 133 bytes
The only answer so far to comply with the "Units are in pixels" rule...
from turtle import*
c=circle
r,n,l=input()
lt(90)
exec'c(r,360/n);fd(l);bk(l);'*n
fd(l)
lt(towards(-r,0)-180)
c(distance(-r,0),360,n)

Add exitonclick() to the end if you don't want the window to close immediately.
Output:
python tangentpoly.py <<< "20, 6, 30":

python tangentpoly.py <<< "100, 8, 200":

for i in n*[0]:c(r,360/n);fd(l);bk(l) -> exec'c(r,360/n);fd(l);bk(l)'*n;

Try it online

T-SQL 440 483
Not going to win any prizes with this one, but I like drawing pictures :)
Edit Expletive! Just noticed I messed up for polygons drawn across the circle.  Fixed at a cost.
SELECT Geometry::UnionAggregate(Geometry::Point(0,0,0).STBuffer(@r).STExteriorRing().STUnion(Geometry::STGeomFromText(CONCAT('LINESTRING(',@r*SIN(a),' ',@r*COS(a),',',@r*SIN(a)+@l*SIN(b),' ',@r*COS(a)+@l*COS(b),')'),0))).STUnion(Geometry::ConvexHullAggregate(Geometry::Point(@r*SIN(a)+@l*SIN(b),@r*COS(a)+@l*COS(b),0)).STExteriorRing())p FROM(SELECT RADIANS(360./@*N)a,RADIANS((360./@*N)-90)b FROM(SELECT TOP(@)row_number()OVER(ORDER BY(SELECT\))-1N FROM sys.types a,sys.types b)t)r

Executed with the following variables
declare @r float = 1.0
declare @ int = 10
declare @l float = 3.0

Run in Sql Server Management Studio 2012+ it will return the following in the spatial results tab.

With
declare @r float = 1.0
declare @ int = 360
declare @l float = 3.0

with
declare @r float = 10.0
declare @ int = 3
declare @l float = 10.0

Expanded out
SELECT Geometry::UnionAggregate(    --group together lines
    Geometry::Point(0,0,0)          --Set origin
    .STBuffer(@r)                   --Buffer to @r
    .STExteriorRing()               --Make it a line
    .STUnion(                       --Join to the floowing tangent
        Geometry::STGeomFromText(   --Create a tangent line
            CONCAT('LINESTRING(',@r*SIN(a),' ',@r*COS(a),',',@r*SIN(a)+@l*SIN(b),' ',@r*COS(a)+@l*COS(b),')'),0)
        )
    ).STUnion( --Generate polygon around exterior points
    Geometry::ConvexHullAggregate(Geometry::Point(@r*SIN(a)+@l*SIN(b),@r*COS(a)+@l*COS(b),0)).STExteriorRing()
    )
    p
FROM(
    SELECT RADIANS(360./@*N)a,      --calclate bearings
        RADIANS((360./@*N)-90)b
    FROM(                           --make enough rows to draw tangents
        SELECT TOP(@)row_number()OVER(ORDER BY(SELECT\))-1N
        FROM sys.types a,sys.types b
        )t
    )r

MATLAB - 233 bytes
function C(n,r,l),t=2*pi/n;c=cos(t);s=sin(t);M=[c,s;-s,c];F=@(y)cell2mat(arrayfun(@(x){M^x*y},1:n));P=F([0;r]);Q=F([l;r]);v='k';t=1e3;t=2*pi/t*(0:t);R=[1:n 1];q=Q(1,R);s=Q(2,R);plot(r*cos(t),r*sin(t),v,[P(1,R);q],[P(2,R);s],v,q,s,v);

Sample function output for n = 8, r = 4, l = 6 (axes included to indicate unit length):

Sample function output for n = 1024, r = 4, l = 2:

I'm nit-picking, but Units are in pixels

@DigitalTrauma: Ah. Didn't notice that. MATLAB figures don't have fixed units; they scale to the window. And it's a moot point anyway. Your LOGO based solution in Python has mine soundly beat. Before today I wouldn't have conceived somebody would port LOGO into Python, but there it is. I'm learning as I go along. :P

Well +1 anyway :)

The image is almost aperture's logo.

HTML + JavaScript (E6) 298
To test, save as an html file and open with FireFox.
Insert the parameters r,n,l into the input field, comma separated, then tab out.
Or try jsfiddle
<input onblur="
[r,n,l]=this.value.split(','),
z=r-~l,t=D.getContext('2d'),w='lineTo',
D.width=D.height=z*2,
t.arc(z,z,r,0,7);
for(C=1,S=i=0;i++<n;)
  t[w](x=z+r*C,y=z+r*S),
  t[w](x-l*S,y+l*C),
  C=Math.cos(a=6.283*i/n),
  S=Math.sin(a),
  t[w](z+r*C-l*S,z+r*S+l*C);
t.stroke()">
<canvas id=D>

Sample output


text:
Convert number bases
What your function must do:
be as short (in bytes) as possible
take 3 inputs that are strings: number , fromdigits, todigits
assume no digit is repeated in fromdigits or todigits
assume fromdigit and todigit contain only alphanumeric characters
assume number is a natural number
output (a string): number converted to frombase
examples:
convert("ff","0123456789abcdef","0123456789")="255"
convert("ee","fecdba9876543210","9876543210")="82"
example code (283 bytes, in python 3.4.1):
def convert(number,fromdigits,todigits):
    x=0
    for digit in str(number):
        x = x*len(fromdigits)+fromdigits.index(digit)
    res=""
    while x>0:
        digit = x % len(todigits)
        res = todigits[digit] + res
        x //= len(todigits)
    return res

For a fastest code challenge, you need to say how you're going to measure the speed of the code. What inputs will be used? On what system will it be measured?

be as short (in bytes) as possible

Then the tag you're looking for is [tag:code-golf].

Almost there! You should specify the format of the input and output. You say "program" but define a function. The default is to allow both. Also, is there a limit to the characters that may be used to represent digits?

Your code handles negative values. Is that a requirement? That's worth clarifying, as well as the fact the numbers are presumably integers rather than floats. Also, it seems clear that the output is a string, but that's worth saying explicitly.

The output of the convert("ff","0123456789abcdef","0123456789") call should be 255 instead of 256

How to convert '0'? The example code returns '', is it correct?

i assume so, since zero=nothing

Python - 101
To get started I basically golfed your example code...
def c(n,f,t,x=0,r=""):
 for d in n:x=x*len(f)+f.index(d)
 while x:l=len(t);r=t[x%l]+r;x//=l
 return r

APL (40)
Can't beat CJam anymore it seems.
{⎕IO←0⋄⍵⍵[N⊤⍨(⌊1+Z⍟N←(⍴⍺⍺)⊥⍺⍺⍳⍵)/Z←⍴⍵⍵]}

This takes the fromdigits and todigits values as its ⍺⍺ and ⍵⍵ arguments, and the number itself as the ⍵ argument, i.e.:
      ('0123456789abcdef'{⎕IO←0⋄⍵⍵[N⊤⍨(⌊1+Z⍟N←(⍴⍺⍺)⊥⍺⍺⍳⍵)/Z←⍴⍵⍵]}'0123456789')'ff'
255
      ⍝ for ease of reading
      convert ← {⎕IO←0⋄⍵⍵[N⊤⍨(⌊1+Z⍟N←(⍴⍺⍺)⊥⍺⍺⍳⍵)/Z←⍴⍵⍵]}
      ('0123456789abcdef' convert '0123456789') 'ff'
255
      ('fedcba9876543210' convert '9876543210') 'ee'
82
      ('0123456789' convert '01') '254'
11111110

Explanation:

⎕IO←0: set the index origin to 0. (APL arrays start at 1 by default and we don't need that here.)
Z←⍴⍵⍵: store the length of ⍵⍵ in Z. This is the base to convert to.
N←(⍴⍺⍺)⊥⍺⍺⍳⍵: look up the index (⍳) in ⍺⍺ of each value in ⍵. These are the digits in the base to convert from. Then decode (⊥) this from the input base, which is the length of ⍺⍺. Store this value in N.
⌊1+Z⍟N: find the amount of digits required to represent value N in base Z.
(...)/Z: replicate Z that many times.
N⊤⍨: encode N into the output base.
⍵⍵[...]: for each digit of that, find the corresponding character in ⍵⍵.

Why do you use 2 character variable names, plus, since those are unicodes, they are 4 bytes each

@Optimizer: the APL charset fits in a byte just fine, and the 2-character variable names are just what APL calls them. ⍺ and ⍵ are function arguments, and ⍺⍺ and ⍵⍵ are the operator arguments. What this code is in fact doing is defining a 'convert' operator that takes two base strings on ⍺⍺ and ⍵⍵, which then gives a function that takes the number to be converted on ⍵.

CJam, 20 bytes
rr:Ff#F,bAbsr:Tf#T,b

Input is like:
ee fecdba9876543210 9876543210

Output:
82

Try it online here


text:
Resolve doubling and tripling actions in Dominion
Inspiration
This question is inspired by the cards Throne Room and King's Court from the popular deck-building card game Dominion.

As part of one's turn, one plays a sequence of actions. These two particular actions cause the next-played action to repeat two or three times*. Other "generic" actions cause specific game effects, but we won't be interested in the particulars, simply labelling them with letters.
The interesting case is when a Throne Room or King's Court affects another Throne Room of King's Court, causing the doubling or tripling effect to itself be doubled or tripled. Long chains of Throne Rooms, King Courts, and multiplied actions can confuse even experienced Dominion players.
Your goal is to write code that correctly resolves these chains, using as few bytes as possible. I'll describe the program requirements before explaining how the chains resolve in the Dominion rules.
*Technically, you choose the action affected as part of resolving Throne Room or King's Court, but this view is cleaner for this challenge.
Program Requirements
Write a program or named function. It should take in the chain of actions played (STDIN or function input), and output or print the resulting chain of actions from the effects of doubling and tripling. Fewest bytes wins.
Input
A string representing the sequence of actions played. Generic actions are represented by capital letters A through Z. The special doubling action Throne Room is represented by the character 2, and the tripling action King's Court by 3,
The number of characters (actions) will be between 1 and 30, inclusive. You may have the input end in a newline if you wish.
Example input: WA23G3GA
Output
A string of capital lettersA to Z. This should be the sequence of generic actions that results from resolving the doubling and tripling effects, in the order than they happen.
You may have the output end in a newline if you wish. There should be no additional characters otherwise.
Example output: WAGGGGGGAAA.
How doubling and tripling works in Dominion
Here, I'll go through how chains of Throne Rooms (2's) and King's Courts (3's) work as per the Dominion rules.
After you play a 2, the next action to be resolved happens twice. So, if you first play 2, then A, you get A happening twice.
2A -> AA

Similarly,
A2BC -> ABBC
3DE -> DDDE
3N2BC3XY2 -> NNNBBCXXXY

Note in the last example that the final 2 had nothing to double, so it had no effect.
The interesting thing happens when doubling or tripling effects are themselves doubled or tripled. For example,
22AB -> AABB

First, you play 2. Then, you play another 2, which is doubled from the previous 2. As a result, the next two actions are doubled. First, the two copies of A resolve. Then, the copies of B resolve.
Note that A is not quadrupled: after the first copy of 2 acts on the first A, the next copy acts on the next unresolved action, which is B. Without the B, we'd have
22A -> AA

where the second copy of 2 is waiting for the next action to double, but no action comes.
Finally, let's look at a complex example.
223BCDE -> BBBCCCDDE

As before, the first 2 causes the second 2 to be doubled. So, the next two actions will be doubled. The first copy of 2 doubles the next action 3, which must be resolved completely before resolving the next copy of 2. The first copy of 3 triples B, and the second copy triples C. Now, the still-waiting second copy of 2 doubles the next still-unresolved action, which is D. After this, no doubling or tripling effects remain, and the final action E simply happens.
Test cases
These are given as (input,output).
(FY, FY)
(A2BC, ABBC)
(3DE, DDDE)
(3N2BC3XY2, NNNBBCXXXY)
(WA23G3GA, WAGGGGGGAAA)
(32, )
(33RST, RRRSSSTTT)
(2A32B2CDEFG, AABBCCDDEEFG)
(A2A323AB2CD2D2E3ABC, AAAAAABBBCCDDDDEEAAABBBC)
(P22LL3Q2Q22T, PLLLLQQQQQTT)
(322322ABCDEFGHIJKLMN, AABBCCDDEEEFFGGHHIJKLMN)

GolfScript (29 26 bytes)
](1/{\1+(3&@*.23-\1$-@+}/;

Online demo
Dissection
This slightly abuses the loose typing of GolfScript. The stack of how many times to repeat subsequent actions starts out as an array and later turns into a string - but 1+ appends a 1 and (3& pops the first value and correctly puts it in the range 0 to 3 regardless of the type change.
](         # Push an empty array under the input string to serve as rep stack
1/{        # Loop over the input string as a series of 1-char strings
           #   Stack is ... reps ch
           #   where the ... covers zero or more strings which will be output
  \        #   Bring the rep stack to the top
  1+(      #   Push a `1` on the bottom of it to avoid underflow and then pop
  3&       #   Coerce to correct range, because if rep stack is a string then
           #   we just got an ASCII value
  @*       #   Apply repetition to the 1-char string: it's now an n-char string
  .23-     #   Duplicate it and remove chars '2' and '3': this becomes output
  \1$-     #   Get the original copy and remove the output string's chars
           #   So the stack is now ... reps output non-output
           #   where non-output is either an empty string or a string of '2's
           #   or '3's
  @+       #   Push non-output onto the repetition stack
}/         # Loop
;          # Pop whatever's left of the repetition stack

I like your trick of pushing 1's under the stack to treat un-multiplied actions the same as multiplied ones. Could you please explain more about how you juggle the various stacks? In particular, what does \ do to "bring the rep stack to the top"?

@xnor, here's the builtins reference. \ swaps the top two items on the stack.

Thanks, I hadn't understood that each stack element was its own stack; I was imagining a single concatenated stack.

@xnor, it's not that each stack item is its own stack; it's that the repetition stack is stored as an array or a string (which is still an array, but treated differently by some builtins). Debug demo which prints the GS stack contents just before the end of the main loop.

Javascript - 162 152 bytes
Minified:
F=I=>{L=c=>S.length;p=c=>L()?S.shift():d=>{};S=[(x=>/\d/.test(x)?(c,b)=>{for(c=p(),b=x;b--;)c();}:c=>s+=x)(m)for(m of I)];for(s='';L();)p()();return s;}

Expanded:
F = I => {
    L = c => S.length;
    p = c => L() ? S.shift() : d => {};
    S = [ (x => /\d/.test( x ) ?
        (c,b) => {
            for( c = p(), b = x; b--; )
                c();
        } : c =>
            s += x
        )(m) for( m of I ) ];

    for( s = ''; L(); )
        p()();

    return s;
}

I'm guessing the stack-based golf languages will kill on this one, since it's basically an exercise in function stacking. :P
Sample Outputs
F('3N2BC3XY2')
"NNNBBCXXXY"

F('WA23G3GA')
"WAGGGGGGAAA"

F('A2A323AB2CD2D2E3ABC')
"AAAAAABBBCCDDDDEEAAABBBC"

F('322322ABCDEFGHIJKLMN')
"AABBCCDDEEEFFGGHHIJKLMN"

F('FY')
"FY"

F('')
""

I'm surprised by how exact a parallel your interpretation of cards as functions is. I expected a stack, but not a literal call stack of functions! Is there not a more concise way to though call a function multiple times? Better yet, a variable number of times to handle the 2/3 cases together?

@xnor: I thought it was clever. ;)  As for your suggestion, your intuition was correct. I've combined the two cases for a savings of 10 bytes. It would ideally be 18 but I've stumbled on what I believe is a bug in Firefox. I should be able to manipulate x directly without first copying it into a variable b scoped to the inner lambda, but Firefox doesn't evaluate the loop condition properly. Specifically, x goes negative and the browser hangs. Try replacing , b = x; b--; with ; x--; and run the input A2A323AB2CD2D2E3ABC. If anyone reading this can figure out why, ...

...I'd be very interested to know. Maybe I'm missing something on how the closures are supposed to work.

C, 115 111 bytes
Uses standard input/output.
Saved 4 by using memset and making the stack go in the other direction.
char*i,X[222],*s=X+99;main(){for(gets(i=X);*i;i++)*i<55?s=memset(s-*s,*i-49,*s+1):putchar(*i)**s?--*s,--i:++s;}

Ungolfed
#include <stdio.h>
#include <stdlib.h>
char I[99], S[99], *i = I, *s = S+66;
int n;
int main()
{
    gets(I);
    for(;*i;)
    {
        if(*i < '5') {
            n = *s;
            s[0] = s[1] = s[2] = *i - '1';
            s += n;
            i++;
        } else {
            putchar(*i);
            if(*s)
                --*s;
            else
                --s, ++i;
        }
    }
    return 0;
}

Python (84)
S='1'*99
R=''
for c in input():q=int(S[0])*c;S=q*(c<'A')+S[1:];R+=q*(c>'3')
print(R)

S is the stack of multipliers (top if front). It's initialized with enough 1's to handle unmultiplied actions.
Depending on whether the current action c is generic or not, we add its multiplied result either to the output R or to the stack of multipliers S.
Everything is represented as a string rather than a list of chars. Because strings are immutable, we unfortunately can't use pop or element assignment on them.


text:
Shrinking numbers
The input is an array of (at least 3, maximum 20) different integers. Each integer is greater than -1000 and smaller than 1000.
Your task is to shrink the numbers by "linearly mapping" them from 0.0 to 1.0. This means the smallest number in the array will be mapped to 0.0, the largest to 1.0.
You get the array as a parameter (inside a function) or stdin/program arguments (you can choose). Print out the result in the format double1;double2;double3;.... The output has to have the same order as the input.
If you want, you can round the output to 2 digits after the decimal point. There must be atleast 1 digit after the decimal point.
The usage of built-in functions (functions which scale down the numbers for you, such as mathematicas Rescale) is disallowed.
Examples:
Input              Output
[5,-20,30]         0.5;0.0;1.0
[1,2,3,4,5]        0.0;0.25;0.5;0.75;1.0
[0,5,100,400]      0.0;0.01;0.25;1.0

(The last output is rounded, otherwise it would be 0.0;0.0125;0.25;1.0)

So even we write a function the result has to be printed? (As opposed to returning a corresponding array of doubles.)

@MartinBüttner Yes, they have to be printed. Built-in functions are disallowed.

" usage of built-in functions (such as mathematicas Rescale) is disallowed." - that's too vague. What functions are disallowed? Only those that solve the full problem (which would be a standard loophole) are?

Wait, so, the input may be a function argument, but the output must be to the screen???

@JanDvorak Yes.

It's still unclear what counts as built-in functions that are disallowed

@Manu What if the resultant number is not a fraction, do we still need a .0 after that ?

@Optimizer Yes. There must be atleast 1 digit after the decimal point.

@Manu - Then all existing answers are incorrect ;) . Trying to fix mines.

Some answers format the output in a different manner (e.g., separating by spaces or as an array). Is that allowed?

@Dennis The format has to match the one shown in the question. This means the numbers are seperated by semicolons.

@Manu I misunderstood your challenge. Ignore my comment :P

The atleast one digit after the decimal point rule needlessly complicates things, as well as the forced string output. In RProgN, the solution could just be ] max /, however, these formatting demands make it ] max / ';' . '1$' '1.0' R '^0' '0.0;' R

I dont really understand what I need to do, i, by iterating over every element, do this toreturn[i] = (arg[i]*1f/arg.maxOf{it}).coerceIn(0f,1f) but somehow it is wrong? what exactly do i need to do?

CJam, 18 bytes
q~_$0=f-_$W=df/';*

Note that the online interpreter wrongfully represents 0d as 0 instead of 0.0.
Example run
$ cjam shrink.cjam <<< '[5 -20 30]'; echo
0.5;0.0;1.0
$ cjam shrink.cjam <<< '[1 2 3 4 5]'; echo
0.0;0.25;0.5;0.75;1.0
$ cjam shrink.cjam <<< '[0 5 100 400]'; echo
0.0;0.0125;0.25;1.0

How it works
q~                    " P := eval(input())         ";
  _$0=                " S := sorted(P)[0]          ";
      f-              " Q := { X - S : X ∊ P }     ";
        _$W=d         " D := double(sorted(Q)[-1]) ";
             f/       " R := { X / D : X ∊ Q }     ";
               ';*    " print(join(R, ';'))        ";

My reaction to this, as a CJam source: Wtf? explanation needed...

Nice way of getting min and max using array index instead of popping and then swapping things around

It's probably my cold speaking, but why do you sort twice? Shouldn't a sorted array stay sorted if a constant is subtracted from each element?

@IngoBürk The sorted array doesn't survive the array access, I think. Which makes sense, because the final result must not be sorted.

@MartinBüttner D'oh. Of course. We need to retain order for the result. Thanks!

JavaScript, ES6, 81 bytes
Thanks to @edc65 for the toFixed trick
F=a=>a.map(v=>((v-n)/d).toFixed(2),n=Math.min(...a),d=Math.max(...a)-n).join(';')

Run it in latest Firefox Console.
This creates a function f which you can invoke like
F([5,-20,30])

why eval(prompt) when a function is allowed? 2)There must be at least 1 digit after the decimal point. 3)no need to store M, just d=M-m

Updated. Although, getting at least 1 digit after decimal is tough

If you want, you can round the output to 2 digits after the decimal point that's the simpler way I think

@edc65 But there is no way to convert 1 to 1.0 except for what I did.

Nope. May I hint?

Be my guest :).

88,2 fixed decimals as allowed by OP: F=a=>alert(a.map(v=>((v-n)/d).toFixed(2),n=Math.min(...a),d=Math.max(...a)-n).join(';')), 97:F=a=>alert(a.map(v=>v-n?v-m?(v-n)/(m-n):'1.0':'0.0',n=Math.min(...a),m=Math.max(...a)).join(';')) // just 2 int values possible, min map to 0 and max map to 1

Ah, toFixed :D . I think we can do away with alert

CJam, 24 23 bytes
l~_$)\(:M\;-\Mf-\df/';*

Input be like:
[5 -20 30]

Try it online here Note that online compiler prints Double 0 as 0 only. Run in the java interpreter which prints correctly.
How it works:
l~                      "Evaluate input and convert each element to double";
  _$                    "Copy the array and sort the copied array";
    )                   "Pop the last element out of the array. This is Max";
     \                  "Swap last two stack elements, bring sorted array on top";
      (:M               "Pop the first element of array and store it in M. This is Min";
         \;             "Bring the remaining of sorted array on top and remove it from stack";
           -\           "Subtract Max and Min and bring the original array to top of stack"
             Mf-        "Push min to stack and subtract it from each array element";
                \df/    "Bring (Double)(Max-Min) to top and divide each array element by it";
                   ';*  "Push the character ; to stack and join the array with it";

Ah, that's a much better idea to get minimum and maximum.

This prints 0;0.5;1 instead of 0.0;0.5;1.0.

@Manu - Yes, trying to fix that. And almost all answers do this only.

You don't need the fix. The Java interpreter represents the Double 0 as 0.0.

Python 2, 72 68 63 56 55
Obviously not as concise as other answers, but anyway:
x=input()
m=min(x)
print[(i*1.-m)/(max(x)-m)for i in x]

Sample run:
[1,100,25,8,0]                  #input
[0.01, 1.0, 0.25, 0.08, 0.0]    #output

Old (68 characters, written in Python 3):
x=eval(input())
y=sorted(x)
print([(i-y[0])/(y[-1]-y[0])for i in x])

You can save one more char by defining m=min(x).

C# 92
Running inside LinqPad
void F(int[]a)
{
   double n=a.Min(),d=a.Max()-n;
   a.Select(x=>((x-n)/d).ToString("0.00")).Dump();
}

Test in LinqPad
void Main()
{
    F(new int[]{5,-20,30});
}
void F(int[]a){double n=a.Min(),d=a.Max()-n;a.Select(x=> ((x-n)/d).ToString("0.00")).Dump();}

Output
IEnumerable<String> (3 items)
0,50
0,00
1,00

APL (15)
(2⍕+÷⌈/)(+-⌊/)⎕

(or, without trains, also 15 characters:)
2⍕V÷⌈/V←V-⌊/V←⎕

This reads the argument from the keyboard and prints the result to the screen.
Explanation:

⎕: read a line from the keyboard and evaluate it
+-⌊/: subtract the lowest item in the array from all items in the array
+÷⌈/: divide each item in the array by the array's highest item
2⍕: format with two decimal places

Test:
      (2⍕+÷⌈/)(+-⌊/)⎕
⎕:
     5 ¯20 30
 0.50 0.00 1.00
      (2⍕+÷⌈/)(+-⌊/)⎕
⎕:
      1 2 3 4 5
 0.00 0.25 0.50 0.75 1.00
      (2⍕+÷⌈/)(+-⌊/)⎕
⎕:
      0 5 100 400
 0.00 0.01 0.25 1.00

Should add the byte count...

Which is 24 bytes only.

@Optimizer: Unless the question states otherwise, every answer is scored using the encoding that yields the smallest byte count. There's an APL codepage that represents every APL character by one byte.

Correct me if I am doing something wrong here, but by default, [tag:code-golf] are counted in bytes and https://mothereff.in/byte-counter#%282%E2%8D%95+%C3%B7%E2%8C%88/%29%28+-%E2%8C%8A/%29%E2%8E%95 page says its 24 bytes. Did I miss something ?

@Optimizer: That gives the byte count in UTF-8, not using the APL codepage.

Ah, I see . . .

Output has to be seperated by semicolons, not spaces.

Pyth, 18
Now with correct formatting!
j\;mc-dhSQ-eSQhSQQ

Test:
$ pyth -c 'j\;mc-dhSQ-eSQhSQQ' <<< '[0,5,100,400]'
0.0;0.0125;0.25;1.0

Explanation:
(implicit)              Q = eval(input())
j\;                     ';'.join(
   m                             map(lambda d:
    c                                         float_div(
     -dhSQ                                              d-sorted(Q)[0],
     -eSQhSQ                                            sorted(Q)[-1]-sorted(Q)[0]),
    Q                                         Q))

The output is not formatted correctly.

@Manu Sorry about that, I've fixed it.

Doesn't creating your own language, which you change over time, slightly stretching the rules? You can obviously just add a new feature to make the program shorter?

@ChrisJefferson I always use the newest version of the language that came out before the problem was asked. Since it's all pushed to Github, it can be verified that I'm not adding anything after the problem is posted. That's the standard CG.SE rule - the language must be older than the question, and I abide by it.

CJam, 30 29 bytes
l~:d_{e>}*\_{e<}*:Mf-\M-f/';*

Expects the input on STDIN like [5 -20 30].
Test it here. (This will print integer 0 and 1 without decimal point, but the Java interpreter does print 0.0 and 1.0.)
Due to a bug I can't shorten {e>}* to :e> although that should be possible as per the spec (which would save 4 bytes when applied to both min and max).
Slightly outdated explanation: (will amend later)
l~:d_{e<}*_@_{e>}*@-\@f-\f/';* "Read and eval the input leaving an array of strings on the stack";
l~                             "Read and eval the input leaving an array of strings on the stack";
  :d                           "Convert all elements to double";
    _                          "Duplicate the array";
     {e<}*                     "Wrap the MIN function in a black and fold it onto the array";
          _                    "Duplicate the minimum";
           @                   "Rotate the stack, pulling the array to the top";
            _                  "Duplicate the array";
             {e>}*             "Same as before, now with MAX";
                  @            "Rotate the stack, pulling the minimum to the top";
                   -           "Subtract to give the total range";
                    \          "Swap range and array";
                     @         "Rotate the stack, pulling the other minimum to the top";
                      f-       "Subtract the minimum from each element in the array";
                        \      "Swap range and array";
                         f/    "Divide each element in the array by the range";
                           ';  "Push a semicolon character";
                             * "Riffle the semicolon into the array";

At the end of the program, the stack contents are printed by default.
I'm sure there is a way to save half of the stack reshuffling, but I'm not that comfortable with CJam yet.

This prints 0;0.5;1 instead of 0.0;0.5;1.0.

@Manu See Dennis's comment on Optimizer's answer. It works fine in the Java interpreter.

APL, 31 characters / 55 bytes
{b←⌊/⍵⋄c←(⌈/⍵)-b⋄{2⍕(⍵-b)÷c}¨⍵}

Old code without digits after decimal point:
{b←⌊/⍵⋄c←(⌈/⍵)-b⋄{(⍵-b)÷c}¨⍵}

Take minimum of vector, take difference between maximum and minimum of vector, subtract the minimum from each element and divide by the difference between min and max.
Edited Code to print two digits after the decimal point:

Octave 25
b=min(l);(l-b)/(max(l)-b)

Assumes input is in l and since it's an interactive shell the result is printed automatically (is this allowed?)

Octave/Matlab does have input though to get user input and mimick STDIN. You can also write a function. Also, does this print the result in the correct format?

And no, just returning and having the shell print it generally doesn't count. Golfscript and the like are different because the language specifiesthat the stack is printed in the end. But this isn't the case for, e.g., Javascript. And I don't think for Matlab/Octave either.

Xojo, 179 bytes
dim x,n as double,k,z as int16,s() as string
n=1e3
x=-n
for each k in a
x=max(x,k)
n=min(n,k)
next
for k=0 to ubound(a)
s.append str((a(k)-n)/(x-n),"0.0#")
next
msgbox join(s,";")

R, 60 bytes
m=min(x<-scan());cat(sprintf("%f",(x-m)/(max(x)-m)),sep=";")

Formatting eats up a lot of bytes due to 0 and 1 by default are trimmed to display nothing past the integer part.

Clojure 63
(fn[v](let[l(apply min v)](map #(/(- % l)(-(apply max v)l))v)))

Doesn't quite follow the rules, since it returns fractions instead of doubles. If that's not acceptable, add 7 bytes
Ungolfed:
(fn [values]
    (let [low (apply min values)]
         (map #(/ (- % low)
                  (- (apply max values) low))
              values)))

Callable like this:
((fn[v](let[l(apply min v)](map #(/(- % l)(-(apply max v)l))v))) [5 -20 30])

Output: (1/2 0 1)

Ruby, 49
f=->a{$><<a.map{|x|(x-l=a.min).fdiv(a.max-l)}*?;}

Explanation:
f=->a{}     # Define a lambda that takes one argument a
$><<        # Print the following to STDOUT
a.map{|x|}  # For each element x
(x-l=a.min) # Find the lowest element of a, assign it to l, and subtract it from x
.fdiv       # Float division (/ truncates)
(a.max - l) # Divide by the maximum minus the minimum
*?;         # Convert the resulting array into a string joined by the ';' character

05AB1E, 13 bytes (Non-competing)
ZsWD1.S*+s/Z/

Try it online!

Q (31) IMPROPER OUTPUT FORMAT
{(%/)(x;max x)-min x}(.:)(0::)0

input
1 2 3

output
0 .5 1

Perl - 60
my@a=sort@ARGV;print map{($_-$a[0])/($a[-1]-$a[0])." "}@ARGV

Java 7, 149 bytes
float[]c(int[]x){int b=1<<31,a=b-1,j=0,l=x.length;for(int i:x){a=i<a?i:a;b=i>b?i:b;}float[]r=new float[l];for(;j<l;r[j]=x[j++]-a)*1f/(b-a);return r;}

Ungolfed & test code:
Try it here.
import java.util.Arrays;
class M{
  static float[] c(int[] x){
    int b = Integer.MIN_VALUE,
        a = b-1, // In Java, Integer.MIN_VALUE - 1 = Integer.MAX_VALUE (and vice-versa)
        j = 0,
        l = x.length;
    for(int i : x){
      a = i < a ? i : a; // Determine min value of array
      b = i > b ? i : b; // Determine max value of array
    }
    float[] r = new float[l];
    for(; j < l; r[j] = (x[j++] - a) * 1f / (b-a));
    return r;
  }

  public static void main(String[] a){
    System.out.println(Arrays.toString(c(new int[]{ 5, -20, 30 })));
    System.out.println(Arrays.toString(c(new int[]{ 1, 2, 3, 4, 5 })));
    System.out.println(Arrays.toString(c(new int[]{ 0, 5, 100, 400 })));
  }
}

Output:
[0.5, 0.0, 1.0]
[0.0, 0.25, 0.5, 0.75, 1.0]
[0.0, 0.0125, 0.25, 1.0]

Vyxal, 5 bytes
g-:G/

Try it Online!
Outputs as arbitrary-precision rationals. Look Ma, no Unicode!
g-    # Subtract the minimum
  :G  # Make a copy and get the maximum of that
    / # Divide (list - min) by the maximum

Output has to be ;-separated :-(

@Adám There’s a meta consensus somewhere, will find once back on computer

Ly, 33 bytes
&n&sr>las<l/uy[';ofl/0L[!f!]pu,];

Try it online!
This is pretty direct translation of the requirements, but there are two things which add code I wanted to avoid...  First, since 0 is a valid number in the list, the code has to explicitly add (and manipulate) a loop iterator on the stack.  And second, since the rules imply that negative numbers should produce a 0 output, there's some extra code for that.  If -0.0 is an acceptable output, the code could be a few bytes shorter. :)
&n&sr                             (1) read input and prep for processing
&n     - read STDIN onto the stack
  &s   - save a copy of the stack
    r  - reverse the stack

     >las<                        (2) find/stash the largest input number
>       - switch to an empty stack
 l      - restore a copy of the input list
  a     - sort the stack
   s    - save the top of stack (largest number) to backup cell
    <   - switch back to the stack with the original input

          l/uy                    (3) print first entry, prep for loop
 l     - load the largest number from the backup cell
  /    - divide to get the 0-1 scaled number
   u   - print as a number
    y  - push the stack size onto the stack

              [';ofl/0L[!f!]pu,]; (4) process 2-N list entries
 [                ]   - loop through all the list entries
  ';o                 - print the ";" field separator
     f                - flip the iterator and next list entry on stack
      l               - load the largest number on the input
       /              - divide to get the 0-1 ratio
        0L            - compare result against 0, looking for "<0"
          [   ]p      - if/then structure, true if result <0
           !f!        - true: make top two stack entries "0"
                u     - print ratio (or "0" if result was <0)
                 ,    - decrement iterator
                   ;  - exit program to avoid print extraneous "0"

If -0.0 is an acceptable output, this 4 bytes shorter version could be used.
 &n&sr>las<l/uy[';ofl/0L!*u,];


text:
Copy-paste master
EDIT: I posted this question searching for a beautiful, original solution to this problem. Therefore, I accepted a user's edited category "popularity-contest". Making this a search for optimal solutions (i.e. runtime, code size etc.) is not my intention.
Copy-paste master
John wants to write this phrase multiple times into a text document:
I am a copy-paste master.

He creates a new, empty text document, and types down the phrase. He wants to copy and paste this phrase on a new line until he reaches at least a certain number of lines. He figures out it would be quicker if, from time to time, he selected all the text written so far, copies again and then resumes pasting.
Assume the following:

At time t = 0 the phrase has been typed for the first time and John begins the copy-paste process.
It takes T1 to Select All (Ctrl+A), Copy (Ctrl+C) and Clear Selection (End) => Operation 1
It takes T2 to press Enter and then Paste (Ctrl+V) => Operation 2
After he has copied the phrase the first time, let N1 be the number of Operations 2 until he does Operation 1 again; then follows N2 times Operation 2, etc., the last set of Operation 2 being done Nk.
Let L be the target (minimum) number of lines.
A solution of the problem consists of the collection: (k, N1, N2, ..., Nk)

A quick example: for L = 10, possible solutions are:

(1, 9)
(2, 4, 1)
(3, 1, 2, 1)

Problem
Given (L, T1, T2), find the solution (k, N1, N2, ..., Nk) that minimizes the total time to reach at least L lines.
P.S.
Obviously the total time is:
T = k * T1 + T2 * SUM(Nj; j=1..k)
And the total number of lines at the end of T is:
L' = PRODUCT(1 + Nj; j=1..k) with the condition L' >= L
EDIT:
At Optimizer's suggestion, I will break down the (3, 1, 2, 1) solution for L = 10:

step 1: copy 1 line, then 1 paste => 2 lines
step 2: copy 2 lines, then 2 pastes => 6 lines
step 3: copy 6 lines, then 1 paste => 12 lines

You're asking for an optimal algorithm, so why score by upvotes instead of code size or runtime?

Can you breakdown (3, 1, 2, 1), explaining what all is happening ? Its a bit hard to grasp how 10 lines were reached using that.

@MartinBüttner I was not sure how to define "optimal", I would like the "beautiful" solution to win. Can I also add a "runtime" contest at the same time?

@Optimizer There are 3 'steps.' He pastes the line once: there are now 2 lines. He copies these lines and pastes them twice: there are now 6 lines. He copies these lines and pastes them once: there are now 12 lines.

Ah, target is just a minimum target ...

Very much related: Minimal keystrokes needed...

@BogdanAlexandru: You can make this a [tag:code-challenge], give a set of test cases, and take the answer with minimum total time over all the test cases.

@justhalf and others: if you want a code-challenge, by all means, please go ahead and make your own post. I have posted this for something else, if you don't like it I don't see why you would down-vote it instead of just search for something else that suits your tastes.

I didn't downvote yours. As you can see, I have already posted my answer, taking "beautiful" to mean "optimal solution with log(L) complexity" and "code with beautiful comments" =). And people who commented here are just suggesting a supposedly more common tag for this challenge, and waiting for your clarification. You see that Martin hasn't replied to your reply yet, and my comment was just a suggestion, you can choose not to follow it. So I think we can still wait some more time to get the discussion going and see how interesting your challenge is.

Python, optimal solution
Note that this problem boils down to this optimization problem (as noted in the question):

Minimize T1*k + T2*sum(N_i)
with prod(1+N_i) >= L

(which interestingly means you can swap the values while still getting the same number of total lines)
When k is fixed, the first term T1*k is constant, and the T2 in second term is immaterial, and the problem becomes:

Minimize sum(N_i)
with prod(1+N_i) >= L

which is equivalent to (by substituting N_i with N_i-1:

Minimize sum(N_i)
with prod(N_i) >= L

for which it is well known that the minimum will be achieved when N_i are equal to k-th root of L. Since the N_is need to be integers, we take the closest value which still give us product greater than L.
So the following code does just that, checking each possible k (at the total complexity of log_2(L)), and taking the solution with minimum total time. Note that this will also give the solution with the lowest k if there are multiple solutions.
Hope the comments in the code will explain further confusion that may arise.
Some sample runs:

Enter L, T1, T2: 10 1 2
(3, 1, 1, 2) with score 11
Enter L, T1, T2: 10 10 10
(2, 2, 3) with score 70
Enter L, T1, T2: 10 10 2
(1, 9) with score 28
Enter L, T1, T2: 10 10 20
(3, 1, 1, 2) with score 110
Enter L, T1, T2: 10 5 0
(1, 9) with score 5
Enter L, T1, T2: 10 0 5
(3, 1, 1, 2) with score 20

Note that the last example has another solution (4, 1, 1, 1, 1) with score 20.
Code:
import math

def compute_score(k, L, T1, T2):
    """ Compute the best possible score given k

    Best score is achieved when the values are as close as possible to the
    k-th root of L, since we are only minimizing the sum of the values.
    """
    # k-th root of L
    k_root = math.ceil(pow(L, 1.0/k))

    # Find out how many of those k values can be reduced by 1,
    # while still maintaining product >= L
    k_pow = float(pow(k_root, k))
    reduction = int(math.floor(math.log(k_pow/L, k_root/(k_root-1.0))))

    # Generate the values
    k_root = int(k_root)
    vals = [k_root-2 if i<reduction else k_root-1 for i in xrange(k)]

    # Compute the score
    score = k*T1 + T2*sum(vals)
    return (score, vals)

def find_min_score(L, T1, T2):
    """ Find minimum possible total time, given L, T1, and T2

    Works by finding minimum possible total time on each possible k.
    Note that k <= ceil(log_2(L)) since N_i >= 1 and so (1+N_i) >= 2, so at
    k = ceil(log_2(L)), N_i = 1 for all i, which is the minimum sum
    """
    # k_max = ceil(log_2(L))
    k_max = int(math.ceil(math.log(L, 2)))

    # Trivial score when k=1
    min_score = T1 + T2*(L-1)
    min_vals = [L-1]
    min_k = 1

    # Find minimum
    for k in xrange(2, k_max+1):
        (score, vals) = compute_score(k, L, T1, T2)
        if score < min_score:
            min_score = score
            min_vals = vals
            min_k = k
    return (min_score, min_k, min_vals)

def main():
    while True:
        L, T1, T2 = map(int, raw_input('Enter L, T1, T2: ').split())
        (score, k, vals) = find_min_score(L, T1, T2)
        print '(%d, %s) with score %d' % (k, ', '.join(map(str, vals)), score)

if __name__ == '__main__':
    main()

CJam, WTH
I thought that I will give it a shot in CJam. I had to write my own minimizing and combination routines as CJam is just a stack operations language.
Here goes the code:
ri:Lri:T;ri:Y;2mLm],:){L,a*{m*{(\+}%}*}%({aa}%+:~{:):*L<!},W%_0=_{_,T*\:+Y*+}:R~@{_R@>@@?_R}/;_,S@S*

Its a bit brute force so for high values of input L it takes a while before finishing.
Input goes like:
10 2 2

Where 10 is the target lines (L), first 2 is T1 and second 2 is T2. For the above input, output is:
2 1 4

Say if you had given input as
10 2 4

i.e. for the same target lines, T2 is more than T1, the output will be
3 1 1 2

Try it online here , but I will recommend the Java way of running the code as mentioned here

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Number sum medley
Winner
CJam, 74 bytes by Optimizer
Task

Take an input of an integer n through the console or a file.
Find the sum of the nth prime, square, triangular number, and cube. Add to that the factorial of the first decimal place of the square root of n and the xth Fibonacci number, where x is the first digit of the square of n.
Print that sum to the console or to a file.

Rules

Entries must complete the task above for all positive integers less than 100.
Standard loopholes are of course not allowed.
Any built-in function that finds primes or tests for primes in any way is not allowed.
This is code golf.

Summary of numbers to sum
nth prime (where 2 is the first)
square of n
nth triangular number (where 1 is the first)
cube of n
factorial of the first decimal place of the square root of n
xth Fibonacci number, where x is the first digit of the square of n (2 is the third Fibonacci number)

Examples
Note: The numbers being summed are included here just for clarity.
Input: 1
Output: 2 + 1 + 1 + 1 + 1 + 1 = 7

Input: 11
Output: 31 + 121 + 66 + 1331 + 6 + 1 = 1556

Input: 99
Output: 523 + 9801 + 4950 + 970299 + 362880 + 34 = 1348487

CJam, 83 76 75 74 bytes
This can be golfed more. Will update when I golf it further.
T1{_2$+}A*]ri:NN*s1<i={X):Xmf,1=T+:TN<}gXNN*_N*N_)*2/Nmqs_'.#)=~,:)1+:*]:+

The online compiler for CJam does not return proper Double numbers(required by mq, root). So try it in the Java version as mentioned on this page

Java, 323
class C {public static void main(String[]s){int n=new java.util.Scanner(System.in).nextInt(),p=2,j,k=1,t=0,a=1,b=0,c;z:for(;t<n;p++){for(j=1;++j<p;)if(p%j<1)continue z;t++;}j=(int)Math.round(Math.sqrt(n)%1*10);for(t=0;t++<j;k*=t);for(c=j=n*n;(j/=10)>9;);for(t=0;++t<j;a+=b,b=a-b);System.out.print(p-1+c+(c+n)/2+c*n+k+a);}}

Ungolfed:
class C {
    public static void main(String[] args) {
        int n = new java.util.Scanner(System.in).nextInt(),                                                                    p = 2,
            j,
            k = 1,
            t,
            a = 1,
            b = 0,
            c;

        // prime
        z:
        for (t = 0; t < n; p++) {
            for (j = 1; ++j < p; ) {
                if (p % j < 1) {
                    continue z;
                }
            }
            t++;
        }

        // factorial
        j = (int) Math.round(Math.sqrt(n) % 1 * 10);
        for (t = 0; t++ < j; k *= t);

        // fibonacci
        for (c = j = n * n; (j /= 10) > 9;);
        for (t = 0; ++t < j; ) {
             a += b, b = a - b);
        }

        System.out.print(p - 1 + c + (c + n) / 2 + c * n + k + a);
    }
}

I think a += b, b = a - b should not have a ) before the semicolon.

Mathematica, 152 136 133 132 bytes
For[n=Input[i=m=0],m<n,If[Divisors@++i=={1,i},m++]];#&@@Fibonacci@IntegerDigits[n^2]+i+3n^2/2+n/2+n^3+Floor[-10(Floor[s=Sqrt@n]-s)]!

I'm first determining the nth prime number in a loop (also avoiding NextPrime - it's not explicitly disallowed but I think it's not intended to be allowed either), and then I'm simply summing all the required numbers in a single expression. There is one simplification: I'm combining n2 and the triangular number n(n+1)/2 into 3n2/2 and n/2.
Input is taking via prompt, which is the closest thing to STDIN you get in Mathematica.

JavaScript (Node.js), 159 bytes
n=>{
f=a=b=1
for(N=n**.5*10%10|0;N;)
f*=N--
for(N=(n*n+"")[0];--N;)
b=a+(a=b)
f+=a+n*(n*n+n+-~n/2)
for(i=2;n;n-=j<=i++)
for(j=1;++j<i;)
j=i%j?j:i
return f+i-1}

Try it online!


text:
Find the simplest value between two values
Goal
Your goal is to find the simplest value in an open interval. In other words, given two values a,b with a<b, output the simplest x with a<x<b. This is a code golf, so fewest bytes wins.
Simplicity
All values in this problem are dyadic rationals, which means their binary expansions are finite, or equivalently, are rationals in simplest form a/2^b for some integer a and non-negative integer b. Integers are dyadic rationals with b=0.
Being simpler means having smaller b, tiebroken by smaller absolute value |a|.
Equivalently in terms of binary expansions, to find the simpler number:

Take the one with a shorter fractional part (fewer binary digits after the point).
In case of tie, take the lexicographically earlier one with length the primary sort, ignoring sign.

So, the numbers in simplicity order are
0, ±1, ±2, ±3, ±4, ...
±1/2, ±3/2, ±5/2, ...
±1/4, ±3/4, ±5/4, ...
±1/8, ±3/8, ...
±1/16, ...
...

There's no need to say which of ±x is simpler because any interval that contains both candidates also contains 0, which is simpler than both.
(A bit of background and motivation: In combinatorial game theory, positions in a two-player games have a numerical value representing magnitude of advantage, with the sign saying which player is favored. This value is determined recursively from the two values resulting from the best move of each player. You might guess that one averages them, but in fact it's the simplest value in between.)
Program requirements
Write, in as few bytes as possible, a program or named function that takes two dyadic rationals a,b and outputs the simplest dyadic rational x with a<x<b. Input can be function input or STDIN, and output can be function return or printing.
Input format
Two dyadic rationals a,b in whatever type your languages use for real or finite-precision binary values (float, double, etc). Fraction or rational types that store the value as a numerator and denominator are not acceptable. If you language has no valid type (and only then), you may use binary strings like 101.1101, or post a comment and we'll work something out.
You are guaranteed that a,b are dyadic rationals and a<b. Integer values will be given like 3.0, not 3.
You can assume you have sufficient precision to store the values, the output, and any intermediate steps exactly. So, you shouldn't worry about precision or overflows. I won't give an explicit bound on inputs, but your algorithm should take a reasonable amount of time on inputs like the test cases.
You may take your two numbers in any reasonable built-in container like pair, tuple, list, array, or set. Structures specifically representing intervals are not allowed though.
Output
The simplest dyadic rational strictly between a and b. The same rules for the input types apply, except outputting 3 rather than 3.0 is OK.
Test cases
(-1.0, 1.0)
0.0
(0.0, 2.0)
1.0
(0.0, 4.0)
1.0
(0.5, 2.0)
1.0
(-3.25, -2.5)
-3.0
(-4, 1.375)
0.0
(4.5, 4.625)
4.5625
(-1.875, -1.5)
-1.75

Related: http://codegolf.stackexchange.com/q/26278/8478

@MartinBüttner "Fraction or rational types that store the value as a numerator and denominator are not acceptable." But if your rational type is just real numbers stored internally as rational for exact precision and you don't use things like .get_denom(), it's OK. Also, the output should be not be written in fraction form.

Ugh, it's getting late and my attention span is apparently dwindling...

Probably should specify that there is at least one representable value between a and b.

@feersum How would that fail to be the case?

Assuming the number is stored in a fixed-precision floating-point format, there is a finite number of possible values. It is possible to choose two numbers that are adjacent to each other in the list of all representable values.

@feersum Thanks. I though this would be handled by "You can assume you have sufficient precision to store the value exactly," but that doesn't guarantee the output can be represented. Will edit.

I posted a discussion question on meta to gather opinion on how to treat machine limits in code golf specs and answers http://meta.codegolf.stackexchange.com/q/2280/20260

Python 2 - 100
I think I revised my entire method for this answer a good 4 or 5 times (which is probably an indication that it's a good code-golf question). I don't know if this answer can be golfed down any more but I do feel as if I'm missing some more clever methodological ways to shorten this.
def f(a,b,i=1.):
    r=0if a<0 else(a*i+1)//1/i
    return-f(-b,-a,i)if b<=0 else r if r<b else f(a,b,i*2)

This code doesn't seem to work for large-magnitude numbers. Note that x + 1 may be equal to x, if x is greater than 2**53.

I didn't intend for overflows or representation limits to be a concern. I've edited to make that clear.

How is that an overflow? It's only the result of an approach that doesn't work.

@feersum "You can assume you have sufficient precision to store the values, the output, and any intermediate steps exactly." Is that not sufficient?

OK, I see you have edited it just now. I prefer the non-watered down version. Or maybe I will make one that uses the intermediate step of adding 2^-1074 until the answer is reached:)

@feersum I had also added "your algorithm should take a reasonable amount of time on inputs like the test cases" in anticipation of that :-P

@feersum You bring up an interesting point, but you could argue with inputs a = 2**53 and b = 2**53 + 4 for example, the desired answer mathematically would be 253 + 1 (not 253 + 2) which I am representing as close as possible with 2**53. It raises the question of whether it is preferable to have the output strictly greater than the lower bound, or to have the output be (potentially) as close to the mathematically correct answer as possible. In any case I suppose it's moot now that the question has been revised so that precision is a non-issue.

These types of ambiguities are interesting and have come up many times before, so I posted a discussion question on meta to gather opinions on how to treat machine limits in code golf specs and answers http://meta.codegolf.stackexchange.com/q/2280/20260

Sorry for such a trivial golf, but you can save a character by using (a*i+1)//1/i and removing the space after the else.

@FryAmTheEggman Every character counts :P

Remove the space between r=0 and if to save one byte

@ace I have absolutely no idea why python accepts this as valid syntax. Is it unintentional? I can't think of any reason for it to be implemented. It doesn't even work with other keywords like the else.

@KSab I don't know why it works either... I just saw it here once and used it ever since

@kSab You can generally have a keyword right after a number because the number is parse as its own unit. But something like 3else starts to parse as scientific notation like 3e4 and fails.

Haskell, 61 88 75 73
p!q|p<0= -(-q)!(-p)|r<q=max r 0|0<1=(2*p)!(2*q)/2where r=toEnum$floor$p+1

this checks if there is a whole number between the two, and if yes, return the smallest one. if not, multiply the numbers by 2, apply them recursively, divide by 2 and return.
at least, this is how it works in my mind. the actual code is a bit different.
thanks to xnor for his rounding magic

I don't think this works for ranges that contain 0. Trying -3!4 gives -3.5, instead of 0. I think you may be assuming that the inputs have the same sign, although, I admit I don't know much about Haskell, am I doing something wrong? (and sorry, if I am)

@FryAmTheEggman negatives in Haskell are a bit annoying. -3!4 is parsed as -(3!4), which should be -3.5. but you are infact right, (-3)!4 is -2.0. I'll fix it when i can

Ah, thanks for that tip :) You might be able to try multiplying (or just returning?) your result by 0 if p*q<0. Again, don't know much about Haskell, but that is usually a good way to check for having different signs.

Java - 157 187 186
Probably could be golfed more.
Thanks to Quincunx for a byte.
void f(float a,float b){for(float i=1,d;;i*=2){for(d=0;d<i*Math.max(Math.abs(b),Math.abs(a));d++){for(float x:new float[]{d/i,-d/i}){if(x<b&&x>a){System.out.print(x);System.exit(0);}}}}}

Brute forces all values of the numerator (positive and negative) while the denominator doubles each time.

I don't think imports are free.

This doesn't work for large values either. E.g. if I call f((float)1e30, (float)1e31) it appears to go into an infinite loop. Or was I just not patient enough?

I edited the rules to not worry about precision or representation issues. Floats are fine.

@ypnypn This is an issue that comes in Java in that you can't do imports without wrapping the function in a class. Here's what I say: You can have a "floating" import statement separate from the function, but the chars in the import statement count, including a char for newline. So this is 189 chars.

@feersum you probably aren't patient enough :)

186 chars: void f(float a,float b){for(float i=1,d;;i*=2){for(d=0;d<i*Math.max(Math.abs(b),Math.abs(a));d++){for(float x:new float[]{d/i,-d/i}){if(x<b&&x>a){System.out.print(x);System.exit(0);}}}}}. Avoiding importing saves it, and you would have needed the static imports. The stuff in the java.lang package are automatically "imported"

ES6, 68 67 59
g=(a,b)=>(x=~~(a+1),b>0?x<b?x*(x>0):g(2*a,2*b)/2:-g(-b,-a))

this is a port of xnor's solution (basically, the new thing in it was that it checked for having 0 in the range by *(a>=0). couldn't do this in Haskell because Haskell has a type system :) )
this is the first time I used ES6 ever, so this might still be golfable.

For the type issue of x*(a>=0), an alternative is max(x,0). Can you do that efficiently in Haskell?

@xnor your rounding magic is ingenious

Also, you can do x*(x>0). I couldn't do that in Python because I can't assign x.

I know this is an old post, but I believe ~~(a+1) is the same as -~a, saving 4 bytes. Also, with some rearrangement, you can save another 3 bytes: g=(a,b)=>b>0?-~a<b?-~a*(~a<0):g(2*a,2*b)/2:-g(-b,-a)

C, 98 bytes
Using a recursive algorithm (and the fact that f(a,b) = f(2*a,2*b)/2).
I also removed some bugs. The right answer is:
float n(float a, float b){return (floor(a+1)<ceil(b))?(a<0?(b>0?0:ceil(b-1)):floor(a+1)):n(2*a,2*b)/2;}

Which, to meet the prerequisites, is 19 bytes longer than the original one (of 79 bytes)
Full code:
#include <stdio.h>
#include <math.h>
float n(float a, float b){return (floor(a+1)<ceil(b))?(a<0?(b>0?0:ceil(b-1)):floor(a+1)):n(2*a,2*b)/2;}
main()
{
    float a = -4.0;
    float b = -1.4;
    printf("%f",n(a,b));
}

Just copy-paste it into a random online c compiler and run it.

Does this give f(-4, 1.375)=0.0? I don't see the code handling that case.

a and b seem to be reversed, and I think you may have misread the question a bit. n(2.1,1.2) gives me 3.0 instead of 1.5, and any integer input, like n(2.0,1.0) will crash because ceil(a)>a is always false.

@FryAmTheEggman but the spec tells to assume that the first parameter is smaller

Does this work on negatives? Your code chooses the smallest whole number in the range, so for example on -7.5, -3.5 this would choose -7 when the result should be -4

@proudhaskeller That is correct, but this code will only exit the recursion when ciel(a)>ciel(b), which will never happen if a, the first parameter, is smaller than b. Also, for -3.5,-7.5 this code returns -3.0, the ceiling of the larger number.

@FryAmTheEggman yes, because you switched the parameters around. I believe he meant to write ceil(a)<ceil(b).

@Gerwin when are you going to fix this?

@proudhaskeller It should be fixed.

@GerwinDox From reading the code, I still don't see how it would give n(-4, 1.375)=0.0. Have you checked the test cases? I wasn't able to actually test your code because I don't know C; if you could link to an online running version, that would help.

Apparently now, 0 is worth more than 1. Ugh. I had to add 19 bytes to keep it running.

Perl (89)
most probably this can still be golfed
sub S{($q,$w)=@_;$m=1,$r=0;until($q<$r&&$r<$w){$r=int$q+1;$r<$w||map$_*=2,$m,$q,$w}$r/$m}

In perl 5.32 (released in June 2020) comparison operators can be chained. This means that you can replace $q<$r&&$r<$w with $q<$r<$w and save four bytes. https://metacpan.org/pod/distribution/perl/pod/perlop.pod#Operator-Precedence-and-Associativity

Python 3: 80 bytes
g=lambda a,b:-g(-b,-a)if b<=0 else int(a+1)*(a>=0)if-~int(a)<b else g(2*a,2*b)/2

Ungofed:
def g(a,b):
    if b<=0:return -g(-b,-a)
    if int(a+1)<b:return int(a+1)*(a>=0)
    return g(2*a,2*b)/2

Can probably be golfed more by changing the if/else structure to and/or. The obvious transformation fails due to non-short-circuiting on the Falsey output of 0, but there's likely a rearrangement that does it.
The space in b<=0 else can't be removed as usual because the start letter e is parsed as part of number literals like 1e6.

can I port your code?

@proudhaskeller Definitely.


text:
Maximum box gap
Task
You have a row of numbered boxes, with some filled with items and some empty. Your job is to output the number of boxes from the first to the last box, inclusive, minus the number of boxes of the largest gap between two filled boxes.
Rules
Your program should handle up to 1000 boxes. Score = size of program in bytes. -50 if you don't use a built-in sorting functionality. -150 if you program in assembly :D All cases will have at least one gap.
Input is a list of n-th boxes that are filled. Standard loop-holes aren't allowed.
Sample Input
9, 5, 4, 2

Functions with a list as input are fine.
Sample Output
5

This is the number of boxes between the 2nd and 9th box, inclusive, subtracted by the number of boxes of the gap between the 5th and 9th box (8 - 3 = 5)

@MartinBüttner I've edited it so hopefully it's clearer.

@MartinBüttner Functions are okay.

Can I assume input to be like [9 5 4 2] ?

Are the box numbers always in descending order? At least one answer seems to assume this. 2. Will the box numbers always be positive integers?

@Dennis No, and the boxes are numbered starting from 1.

So, if I understood correctly, 9 4 5 2, 9 4 2 5 and all other permutations of 9 5 4 2 should all yield 5. Correct?

@Dennis Not if the maximum difference between two adjacent numbers is larger/smaller than before.

@Shujal: The way Martin, Optimizer and I interpreted the question, first and last box refer to the boxes with the lowest and highest number, and gaps also refers to the filled boxes in their natural order rather than their order in the array.

@Dennis Ok, now I get it... I was confused because the boxes were next to each other in the array and no other examples were given. I updated my answer to match the requirements.

CJam, -19 -22 -23 (27 bytes - 50 bonus)
Vq~_:+,\&_(+]z{~-~:Xe>}/X+z

Try it online.
Example run
$ cjam box-gap.cjam <<< '[9 5 4 2]'; echo
5

How it works
V                              " V := 0                                          ";
 q~                            " Q := eval(input))                               ";
   _:+,                        " S := range(sum(Q))                              ";
       \&                      " T := S ∩ T          # Preserves the order of S. ";
         _(+                   " U := T[1:] + [T[0]]                             ";
            ]z                 " Z := zip(T, U)                                  ";
              {       }/       " for (X,Y) ∊ Z:                                  ";
               :-~:Me>         "   V := max(V, M := ~(X - Y))                    ";
                        M+z    " R := abs(V + M)                                 ";

CJam, -8 (43 42 bytes - 50 bonus)
l~:A{e>}*A{e<}*-)A{_A\-f{-z}{e<}*}%{e>}*(-

Using tips by @Dennis!
Try it online here
Input is like:
[9 5 4 2]

The bug with folding e< and e> is really annoying, isn't it? ;)

Yeah, 9 extra characters :(

You can use f{-z} instead of \f-{z}%. (I was going to suggest :z, but that doesn't seem to work either.)

Yeah, too many non : supported operations :(

Sadly. You don't need the \ before f.

Nice! I wished these things were more properly documented..

Mathematica, 44 bytes
f=Max@#-Min@#-Max[RotateLeft[l=Sort@#]-l]+2&

Defines a function that takes one argument in form of a list {9, 5, 4, 2}.

Wow, you're fast. What does purpose does RotateLeft have?

@qwr Well, it rotates the array to the left ^^. So {2,4,5,9} becomes {4,5,9,2}. Subtracting the original (sorted) list, gives me all gaps (plus one), i.e. {2,1,4,-7}. The last element is of course useless, but since it's always negative it doesn't matter for Max.

APL (Dyalog 14) (34 - 50 = -16)
{⎕ML←3⋄(1+V-⌊/⍵)-⌈/≢¨⊂⍨~⍵∊⍨⍳V←⌈/⍵}

This is a function that takes a list.
Or, for the same amount of characters:
⎕ML←3⋄(1+V-⌊/B)-⌈/≢¨⊂⍨~B∊⍨⍳V←⌈/B←⎕

This reads the list from the keyboard.

Python 2 - 54 (117104-50)
x=input()
M=max(x)-min(x)+1
X=['1']*M
for i in x:X[i-min(x)]='0'
print M-len(max("".join(X).split('0')))

A program that pretends that the buckets are real, then awkwardly splits them into groups. Takes input like 9,5,4,2.

authors: Стас Стадниченко


text:
The Reaction Time Game
Game
The game is simple. Test the user's response time by asking them to enter the correct value that is displayed on the screen in the shortest time possible. Each round of the game will be as follows:

Show Value ----> Get Response ----> Check Response ----> Report Response Time

Example
ROUND ONE
---------
COMPUTER : G
USER     : G
CORRECT INPUT, TIME = 0.26 SECONDS

Code

You may use any language or program.
Do not use third party libraries, except GUI libraries.
(as suggested by marinus)
You may choose between CLI and GUI.

Points

+12 for the shortest code
-2 for every byte after the 1024th byte
+8 for GUI
+8 for showing questions (eg: 4 + 2 = ?) (rather than static values shown in the example above. There must be at least 10 questions.)
+2 for random intervals between each round
+4 for reporting average response time (in a set of 10 rounds)
+4 for quickly vanishing questions/values
(questions/values stays on screen only for a short interval of time. The vanish time must be less than or equal to 1 seconds.)

You must, in your answer, calculate the total points you have scored. eg (+12 (-2x3) +4 = 10)

The answer with the most points wins.

You should specify the exact prompt texts, because they will affect the character count significantly. Likewise you should specify what a GUI needs to contain to be sufficient. Also how long should the prompt be visible if it does vanish for the last bullet point?

@MartinBüttner It is a trade-off between shortest code(+12) vs question prompts(+8). There must be minimum 10 questions. The vanish time must be less than or equal to 1 seconds.

Do they have to enter in the correct answer for it to register as "time" for reaction?

Do we have to output exactly like in your example after each correct output ?

'Do not use third party libraries.' That kind of makes it hard to write a GUI if you're on Linux.

@EliasBenevedes Yes the input must match the question/value shown.

@Optimizer No, you may just report the time. If you are providing average after 10 rounds, separate it with a comma or a newline character

@EliasBenevedes I'm sorry, what other questions?

Never mind, you were getting to them :P

@marinus I know python has tkinter... hmm.. should I change that rule?

@RenaeLider: Perhaps 'No third party libraries, except GUI libraries'. I assume you put that rule there to stop people from just using a library that answers the question, and this will still stop that.

@RenaeLider If the user enters incorrect answer, do we ignore that answer and start again ? Asking as it might impact the average of 10 answers timings.

@RenaeLider Same for when a question gets vanished.. Do we simply ignore that turn ?

@Optimizer Ignore the incorrect answer and ask another one. Only 10 correct answers must count towards the final result.

JavaScript, ES6 352 340 335 bytes, Potential score : 2 + 8 + 12 + 4 + 4 + 8 = 38
<script>r=Math.random,s=setTimeout;T=N=0;a=_=>(S=s(_=>(C=eval(G.innerHTML=((k=~~(r()*5))+~~(r()*5))+'-'+k),t=new Date,R=s(_=>C=G.innerHTML=a(clearTimeout(S)),r()*1e3)),r()*2e3+1e3),'');document.onkeyup=E=>{clearTimeout(R);E.key==C&&++N&&(T+=(X=new Date-t))&&alert([X,N%10?'':T/10]);C=G.innerHTML=a(N%10||(T=0))};a()</script><a id='G'/>

or try this JSFiddle on latest Firefox.
Working:

Shows a random question in form of X-Y after a random interval of [2,4] seconds.
Waits for a keypress till a random time in an interval of [1,2] seconds, after which, clears the input and moves to step 1.
If correct number is pressed, alerts the time in milliseconds.
If this is the tenth (or rather every tenth) correct answer, show the average time in milliseconds for the last 10 correct answers after a comma.
Empties the input area, goes to Step 1 again.

Please comment if something is incorrect or if you have any doubts.

JavaScript (E6) 305 bytes. Score 8+8+2+4=22
Rusty GUI, but GUI it is. Try in FireFox/FireBug console.
At the time shortest code, but I don't claim the 12 points. Waiting for some more answer.

(Q=i=>(
  i&&(t=r=x=y=0,msg=''),
  w=~new Date(),
  v=prompt(msg+'\nRound '+ ++r+': '+(a=1+t%9)+'+'+(b=1+(t>>4)%9)+'=?'),
  u=~new Date(),
  v-a-b?(++x,msg='Wrong'):(++y,msg='OK Time '+(p=w-u)/1000+' sec'),
  t+=p,
  r<10?setTimeout(Q,u%2000)
  :confirm('Wrong '+x+', OK '+y+' in Avg time '+(t/y/1000)+' sec\nRepeat?')&&Q(1)
))(1)

Since you cannot anyways get the last 4 point bonus, do you mind if I consider this your final submission in order to shorten my submission ?

@Optimizer I still could shorten it a bit - millisec instead of sec, less text ...

Ruby (237)
def measure_time(v)
  t = Time.now
  puts "Enter the value: #{v}"
  result = gets.chomp
  if result == v
    puts "CORRECT INPUT, TIME = #{(Time.now - t).to_f(2)} SECONDS"
  else
    puts "Incorrect"
  end
end

WIP, Python, 366 bytes, Potential score : 8 + 4 = 12
import msvcrt as x
import random as r
import time,os
t=0
while t<11:
    time.sleep(1)
    n=r.randint(1,4)
    m=r.randint(1,4)
    print(str(n)+"+"+str(m)+"?")
    time.sleep(.1)
    t1=time.clock()
    os.system('cls')
    c=x.getch()
    if int(c)==n+m:
        print("Rct time:"+str(time.clock()-t1))
    else:
        print("Wrong char")
    time.sleep(1)
    t+=1

Kivy Application 983 bytes, 26 points (8+8+2+4+4)
I used Python's application framework, Kivy, to create a GUI, just under the 1024 byte penalty.
The game starts with a textbox. Once you click it, a question of the form A+B or A*B, where A,B are between 1 and 10, is shown. To have quick input the user's answer is read as soon as the length of text in the textbox is the same length as the length of the correct answer. For example, if 7*4 is shown, the user's input will be read as an answer once they have entered at least two characters. If the user enters the correct value their response time in milliseconds is shown, otherwise "W" is displayed. The user's input and the question will immediately be hidden, followed by the next question displayed after a random interval of time between 0 and 1 seconds. Every time the user inputs 10 correct responses their average response time is shown for those ten responses.
To run this code you will need a Python interpreter with the Kivy library, and you will want to place both the python file and the kv file in the same directory and name the kv file g.kv. Then you can run the python file as usual.
Python File
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.clock import Clock as K
from random import randint as R, random as Q
import time

class GApp(App):
    def build(s):
        g=G()
        K.schedule_interval(g.P, 0.01)
        return g

class G(Widget):
    def __init__(s):
        super(G, s).__init__()
        s.c=0
        s.t=10*[0]
        s.o=['+','*']

    def on_touch_up(s,t):
        s.U(0)

    def U(s,J):
        s.q.text=str(R(1,10))+s.o[R(0,1)]+str(R(1,10))
        s.i=int(round(time.time()*1000))

    def P(s,J):
        A=s.r
        B=s.q
        C=s.u
        if s.c==10:
            A.text+=";"+str(sum(s.t)/10)
            s.c=0
        try:
            S=str(eval(B.text))
        except:
            return

        if C.text!=S and len(C.text)>=len(S):
            A.text="W"
            B.text=""
            C.text=""
            K.schedule_once(s.U, Q())

        if C.text==str(S):
            s.t[s.c]=int(round(time.time()*1000))-s.i
            A.text=str(s.t[s.c])
            s.c+=1
            C.text=""
            B.text=""
            K.schedule_once(s.U,Q())
GApp().run()

Kv File
#:kivy 1.0.9
<G>:
    u:u
    r:r
    q:q
    Label:
        center:100,400
        text: "A"
    Label:
        center:100,300
        text: "Q"
    Label:
        id: q
        center:200,300
    TextInput:
        id: u
        center:200,400
    Label:
        id: r
        center:100,200

JAVA: (8+8+2+4+4) = 26
Not going for shortest, just grabbing all bonus points first:
Code: (999 Bytes)
import java.awt.*;
import java.util.*;
import java.util.concurrent.*;
import javax.swing.*;

class Q
{
    public static void main( String[] z ) throws Exception
    {
        Random r = new Random();

        int v = 0;
        String x = "FIRST ROUND";

        ScheduledExecutorService e = Executors.newScheduledThreadPool( 1 );
        for( int i = 0; i < 10; ++i )
        {
            int a = r.nextInt( 10 );
            int b = r.nextInt( 10 );
            long s = System.currentTimeMillis();
            ScheduledFuture< ? > f = e.schedule( ( ) -> Window.getWindows()[ 0 ].dispose(), 3, TimeUnit.SECONDS );
            String c = JOptionPane.showInputDialog( x + "\n" + a + "+" + b + "=" );
            if( ( a + b + "" ).equals( c ) )
            {
                long t = System.currentTimeMillis() - s;
                x = "CORRECT :" + t + "ms";
                v += t / 10;
            }
            else
            {
                x = "WRONG";
                v += 300;
            }
            f.cancel( true );
            Thread.sleep( r.nextInt( 1000 ) );
        }
        e.shutdown();
        JOptionPane.showMessageDialog( null, "Average: " + v + "ms" );
    }
}

APL(72), Score: 12+2+8=22
{a←?9⋄c←?9⋄b←⎕TS⋄⎕←a,'+',c⋄d←(⎕TS-b)×⎕=a+c⋄⎕←(5⌷d×60)+d[6]+7⌷d÷999⋄⎕DL(?⌊*9)÷*8}¨⍳⌊*9

Gets two random numbers between 1 and 9. Adds them together and asks the user the answer. If the answer is correct, it prints the reaction time in seconds. Else it prints 0. Repeats e^9=8103.08... times. Breaks when given a vector, a command or a variable name. But you could feed it ⌊*1 (floor(e^1))and it would happily interpret it as 2. Gives a negative score if the answer is not given within the same hour because of the dumb system of APL timestamps.