# Question
Title: Tension on a Graph, Part I: A Wavy String
Let's plot a function *f(x) = sin(πx) + 0.5 sin(3πx)* over the domain *\[-3,3\]*. We can interpret this as a loose string lying on a board. Now let's drive *n* nails into the board at positions *(x1, y1)* to *(xn, yn)*, where the *xi ∈ (-3,3)* and *yi ∈ \[-1,1\]*. Imagine that there are two eyelets at the end of the string, that is at positions *(-3,0)* and *(3,0)*. We can now take the ends of string and pull the through the eyelets until the string is taut. This will deform our graph into a piecewise linear function.

Some pictures might help. Take 8 nails at *(-2.8, -0.7), (-2.5, -0.9), (-1.2, .2), (-0.5, .8), (0.5, .4), (1.2, -0.9), (1.5, -0.6), (1.8, -0.8)*. The following three plots show the process described above:

For larger version: Right-click --\> Open in new tab

And here is an animation of the string tightening if you have some difficulty visualising it:

## The Challenge

Given a list of "nails" (which is not necessarily sorted), plot those nails and the taut string if it starts from the shape of the above function *f*.

You may write a program or function and take input via STDIN, ARGV or function argument. You can either display the result on the screen or save an image to a file.

If the result is rasterised, it needs to be at least 300 pixels wide and 100 pixels tall. The coordinate range from (-3,-1.1) to (3,1.1) must cover at least 75% of the horizontal and vertical extent of the image. The length scales of *x* and *y* do not have to be the same. You need to show the nails (using at least 3x3 pixels) and the string (at least 1 pixel wide). You may or may not include the axes.

Colours are your choice, but you need at least two distinguishable colours: one for the background and one for the nails and the string (those may have different colours though).

You may assume that all nails are at least 10-5 units away from *f* (so that you don't need to worry about floating-point inaccuracy).

This is code golf, so the shortest answer (in bytes) wins.

## More Examples

Here are two more (simpler) examples:

```
{{-2.5, 1}, {-1.5, -1}, {-0.5, 1}, {0.5, -1}, {1.5, 1}, {2.5, -1}}

```

(The string coincides with the *x*-axis.)

```
{{-2.7, -0.5}, {-2.3, -0.5}, {-1.7, 0.5}, {-1.3, 0.5}, {-0.7, -0.5}, {-0.3, -0.5}, {0.5, 1}, {1.5, -1}, {2.5, 1}}

```

## Want another Challenge?

Here is Part II!

# Answer
## Python ~~\+ Pycairo~~, ~~727~~ ~~708~~ ~~608~~, + PyLab, 383

```
from pylab import*
def f(N):
 def P(u,w,N):
    T=lambda v,p:(C(v-u,p-u)>0)==(C(w-v,p-v)>0)==(C(u-w,p-w)>0);M=[(i,n)for i,n in enumerate(N)if T(V([n[0],sin(pi*n[0])+sin(3*pi*n[0])/2]),n)]
    if M:i,n=max(M,key=lambda n:C(n[1]-u,w-u)**2);M=P(u,n,N[:i])+[n]+P(n,w,N[i+1:])
    return M
 V=array;C=cross;a=V([3,0]);plot(*zip(*([-a]+P(-a,a,map(V,sorted(N)))+[a])));N and scatter(*zip(*N));show()

```

**Example**

```
f([(-2.8,-0.7),(-2.5,-0.9),(-1.2,0.2),(-0.5,0.8),(0.5,0.4),(1.2,-0.9),(1.5, -0.6),(1.8, -0.8)])

```

**How it works**

> Suppose we know that the taut string passes through two points *A* and *B* (we can always start with
> *A = (-3, 0)* and *B = (3, 0)*.) As we pull the string, it "wants" to take the shortest path possible between *A* and *B*, that is, ideally, the segment *AB*. However, if there are any nails in the area bounded by the function (*sin πx + ...*) and *AB*, then at least one of them must block the string. In particular, the nail(s) farthest away from *AB* within the said area must block the string. Hence, if *C* is this nail, we know that the taut string must pass through *C*, in addition to *A* and *B*. We can now repeat the process for the segments *AC* and *CB*, and continue in this fashion until eventually there are no more intervening nails.
> This is a binary divide-and-conquer algorithm with a linear scan in each step, so it has a best-case complexity of *O(n log n)* and worst-case complexity of *O(n2)*.
> 9 votes

# Answer
# Python + pylab, 576 bytes

### Algorithm:

> I interpreted the problem as finding the shortest path from *(-3, 0)* to *(3, 0)* such that a vertical line segment connecting a point on the path to a point on *f(x)* never crosses a nail.
> At each *x* where exists at least one nail, find the least upper bound and greatest lower bound given by the nails at that *x*. Consider the points given by these bounds plus the starting and ending points to be the vertices on a graph. Add an edge with weight given by the Euclidean distance between two vertices iff the line segment between them falls within the upper and lower bounds for each intervening x coordinate. Find the shortest path on this graph.

### Example with 27 random points:

```
(-0.367534, -0.722751), (-0.710649, -0.701412), (1.593101, -0.484983), (1.771199, 0.681435), (-1.878764, -0.491436), (-0.061414, 0.628570), (-0.326483, -0.512950), (0.877878, 0.858527), (1.256189, -0.300032), (1.528120, -0.606809), (-1.343850, -0.497832), (1.078216, 0.232089), (0.930588, -0.053422), (-2.024330, -0.296681), (-2.286014, 0.661657), (-0.009816, 0.170528), (2.758464, 0.099447), (-0.957686, 0.834387), (0.511607, -0.428322), (-1.657128, 0.514400), (1.507602, 0.507458), (-1.469429, -0.239108), (0.035742, 0.135643), (1.194460, -0.848291), (2.345420, -0.892100), (2.755749, 0.061595), (0.283293, 0.558334),

```

**Golfed**

What appears as several spaces of indentation in the `for j in R(i&~1)` loop should actually be a tab.

```
from pylab import*
P=((3,0),(-3,0))+input()
X=sorted(set(zip(*P)[0]))
l=len(X)*2
if l>4:scatter(*zip(*P[2:]))
f=lambda x:sin(pi*x)+sin(3*pi*x)/2
B=[[max([-9]+[p[1]for p in P if x==p[0]and p[1]<f(x)]),min([9]+[p[1]for p in P if x==p[0]and p[1]>f(x)])]for x in X]
b=zeros(l);b[2:]=inf
v=list(b)
R=range
for i in R(l):
 for j in R(i&~1):
    A=B[j/2][j&1];D,d=B[i/2][i&1]-A,X[i/2]-X[j/2];K=1;c=b[j]+norm((d,D))
    for k in R(j/2+1,i/2):C=A+D/d*(X[k]-X[j/2]);K&=C<B[k][1];K&=C>B[k][0]
    if(c<b[i])&K:b[i]=c;v[i]=j,(X[j/2],A)
l-=2
s=P[:1]
while l/2:l,p=v[l];s+=(p,)
plot(*zip(*s))
show()

```

**Ungolfed**

```
from pylab import*
P = input()
Xn,Yn = zip(*P)
X = set(Xn+(3,-3))
f = lambda x:sin(pi*x)+sin(3*pi*x)/2
ylb = {x: max([-9]+[p[1] for p in P if p[0] == x and p[1] < f(x)]) for x in X}
yub = {x: min([9]+[p[1] for p in P if p[0] == x and p[1] > f(x)]) for x in X}
ylb[-3] = yub[3] = ylb[3] = 0
X = sorted(X)
l = len(X)
best = zeros((l,2))
best[1:] = inf
prev = [ [0,0] for i in range(l) ]
for i in range(l): # calculate min path to X[i] lb or ub
  for ib in 0,1:
    for j in range(i): # point to come from
      for jb in 0,1:
          Y2, Y1 = (ylb, yub)[ib][X[i]], (ylb, yub)[jb][X[j]]
          dy,dx = Y2 - Y1, X[i] - X[j]
          if all([Y1 + dy/dx*(x - X[j]) < yub[x] and Y1 + dy/dx*(x - X[j]) > ylb[x] for x in X[j+1:i]]):
             c = best[j][jb] + (dy**2+dx**2)**.5
             if c < best[i][ib]:
                 best[i][ib] = c
                 prev[i][ib] = j, jb, (X[j], Y1)
j, jb = l-1,0
pts = [(3,0)]
while j:
    j, jb, p = prev[j][jb]
    pts += [p]
plot(*zip(*pts))
scatter(Xn,Yn)
show()

```
> 3 votes

---
Tags: code-golf, graphical-output
---


title: It’s time to do the math

text:
# Question
Title: It’s time to do the math
## Introduction

This is one of my favorite math puzzles.

Given a digit (say 3) and the number of times to use that digit (say 5), generate 10 expressions which result to 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10 using just +, −, ×, ÷, ^ and √ (root) (brackets are allowed to group operations).

For example:

```
(3^3 + 3)/(3 + 3) = (33 - 3)/(3 + 3) = 3 + 3/3 + 3/3 = 5

```

Note that all of the above use five 3’s and the mathematical operations and result to 5. You can also use a 3 before √ to denote a cube root. Same goes for using 4 before √ to denote a fourth root.

Also note that two 3’s can be used to form 33, or three 3’s can be used to form 333 and so on.

## Challenge

* You will be given two numbers *(both ranging from 1 to 5)* as a function argument, STDIN or command line argument.
* The first number denotes which digit to use and the second number denotes the number of times that digit is to be used in the expression.
* Your program should output an array of size 10 (or 10 space-separated numbers) where each element denotes whether a mathematical expression (using just the allowed operators) resulting into the `(index + 1)` number is possible or not using a truthy/falsy value.

For example, if the input is

```
1 3

```

Then the output should be

```
[1, 1, 1, 0, 0, 0, 0, 0, 0, 1]

```

because only 1, 2, 3 and 10 can be expressed using three 1’s.

## Score

* This is a so the minimum code length in bytes wins.

## Bonus

### Print-em-all \[−50\]

Subtract 50 from your score if the output array elements are equal to the total number of plausible combinations to get the `(index + 1)` value instead of truthy or falsy values.

For example, if there are only 3 possible combinations of five 3’s which result to 5, then the output array’s 4th entry should be 3.

### Extreme Maths \[−100\]

Subtract 100 from your score if the output array elements contain at least one of the actual expressions which result to the `(index + 1)` value.

For example, if using five 3’s, the output array’s 4th entry can be either `(3^3 + 3)/(3 + 3)`, `(33 - 3)/(3 + 3)` or `3 + 3/3 + 3/3`

### Overkilled \[−200\]

Subtract 200 from your score if the output array elements contain all possible combinations (separated by `|`). This bonus is added on top of the *Extreme Maths* bonus, so you get −300 in total.

For example, if using five 3’s, the output array’s 4th element should be `(3^3 + 3)/(3 + 3)|(33 - 3)/(3 + 3)|3 + 3/3 + 3/3`

**Note:** Any two expressions to achieve the same result should be logically different with a different approach in both of them.

For instance, to get 5 using five 3’s, `3 + 3/3 + 3/3` is same as `3/3 + 3 + 3/3` or `3/3 + 3/3 + 3` because the same approach is taken for each of them. `(3^3 + 3)/(3 + 3)` and `(33 - 3)/(3 + 3)` differ, as the 30 in the numerator is achieved via different approaches.

**UPDATE** : After going through all answers, it was found that all answers had imperfections due to edge cases of unary `-` and √. Thus, missing those edge cases was considered okay as far as completeness of answers is involved.

This is a tough question, but a rather interesting one.

Happy golfing!

# Answer
> 1 votes
# Python 3 (imperfect), 449 - 300 = 149

Suffers from all the same shortcomings as KSab's solution: no unary operators, fully parenthesized, contains equivalent expressions like `(1+1)+1` and `1+(1+1)`. I eliminated exact duplicates by passing the results to `set()`. The output could be a bit uglier to save a few bytes, but I like it this way. I also didn't do nth roots because it doesn't seem like they buy you much in this problem.

```
R=range
E=lambda z:eval(z.replace("^","**"))
def m(d,n):_=R(1,11);s={i:[]for i in _};r=R(1,n);n<2 and s[d].append(str(d));d=str(d);t=[[(d*i,i)for i in r]]+[[]]*n;h=[];[(h.append("("+A+o+B+")"),t[l].append((h[0],a+b))if a+b<n else E(*h)in _ and s[E(*h)].append(h[0]),h.pop())for l in r for j in R(l)for A,a in t[j]for k in R(l)for B,b in t[k]if a+b<=n for o in"+-*/^"if(o=="^"and-~-(0<E(B)<9)or 0==E(B)and"/"==o)-1];[print(i,set(s[i])or'')for i in _]

```

This will take several minutes to run if the second argument is 5. Test by calling `m(digit, number)`:

```
>>> m(1,3)
1 {'((1*1)^1)', '(1^(1+1))', '((1-1)+1)', '((1/1)/1)', '((1*1)*1)', '((1^1)/1)', '(1*(1*1))', '(1^(1*1))', '(1+(1-1))', '(1^(1^1))', '((1^1)*1)', '(1^(1/1))', '((1/1)*1)', '(1-(1-1))', '(1/(1^1))', '(1/(1*1))', '(1/(1/1))', '(1*(1^1))', '((1+1)-1)', '((1*1)/1)', '((1^1)^1)', '(1*(1/1))', '((1/1)^1)'}
2 {'(1*(1+1))', '((1^1)+1)', '((1+1)/1)', '((1*1)+1)', '((1+1)^1)', '(1+(1*1))', '((1/1)+1)', '(1+(1^1))', '(1+(1/1))', '((1+1)*1)'}
3 {'((1+1)+1)', '(1+(1+1))'}
4
5
6
7
8
9
10 {'(11-1)'}
>>> m(3,3)
1 {'((3/3)^3)'}
2 {'(3-(3/3))', '((3+3)/3)'}
3 {'(3-(3-3))', '((3-3)+3)', '((3/3)*3)', '(3*(3/3))', '(3/(3/3))', '((3+3)-3)', '(3^(3/3))', '(3+(3-3))', '((3*3)/3)'}
4 {'((3/3)+3)', '(3+(3/3))'}
5
6 {'((3*3)-3)'}
7
8
9 {'(3+(3+3))', '((3+3)+3)', '((3^3)/3)'}
10

```

# Answer
> 4 votes
# Python (imperfect) ~~493~~ 474 - 300 = 174

There are a fair number of issues with this solution, firstly that it ignores any exponent that is too large (any in which the exponent is greater than 100). I actually don't think this removes any possibilities for inputs less than or equal to 5, but I'm not 100% sure.

Another thing is that it does not consider any unary square roots, as it would get complicated (any solution with any term equal to 0 or 1 would produce an infinite number of solutions). It also does not consider any unary negation (the '-' symbol) for the same reason, as well as the fact that I'm not actually sure if the question asked for it.

I also considered what criteria should decide if two expressions were equivalent, but I couldn't find a way to rigorously define it in a way I found to be intuitive, so (for now at least) I didn't implement anything like that. This does mean that it outputs quite a few results, and it also uses parenthesis in a fairly naive way.

On a side note I think that this might include the longest single line of code I've written, especially before it was fully golfed.

```
R=range
F=lambda s:lambda a,b:eval(s)
L=lambda D,N:[(int(str(D)*N),str(D)*N)]+[(o(u,v),"(%s%s%s)"%(s,c,t))for p in R(1,N)for u,s in L(D,p)for v,t in L(D,N-p)for c,o in[('+',F('a+b')),('-',F('a-b')),('*',F('a*b')),('/',F("1.*a/b if b else''")),('^',F("''if(a<0 and int(b)!=b)|(a and b<0)|(b>99)else a**b")),('v',F("b**(1./a)if a and(a>=0 or b)and(b>=0 or int(1./a)==1./a)&(1./a<99)else''"))]if o(u,v)!='']
A=L(*input())
for i in R(11):
 for v,s in A:
    if v==i:print i,s[1:-1]

```

Example: ('v' represents '√')

```
2,3

0 2*(2-2)
0 2v(2-2)
0 (2-2)*2
0 (2-2)/2
0 (2-2)^2
1 2^(2-2)
1 2-(2/2)
1 2v(2/2)
1 (2/2)^2
2 2v(2+2)
2 2+(2-2)
2 2-(2-2)
2 2v(2*2)
2 2*(2/2)
2 2/(2/2)
2 2^(2/2)
2 2v(2^2)
2 (2+2)-2
2 (2+2)/2
2 (2-2)+2
2 (2*2)-2
2 (2*2)/2
2 (2/2)*2
2 (2/2)v2
2 (2^2)-2
2 (2^2)/2
3 2+(2/2)
3 (2/2)+2
6 2+(2+2)
6 2+(2*2)
6 2+(2^2)
6 (2+2)+2
6 (2*2)+2
6 (2^2)+2
8 2*(2+2)
8 2*(2*2)
8 2*(2^2)
8 (2+2)*2
8 (2*2)*2
8 (2^2)*2

```

# Answer
> 3 votes
## Python 3 – ~~349~~ 346

```
r=range
l=lambda s:eval("lambda a"+s)
def T(u,f,X,Y):
    try:return u(f(X,Y))
    except:0
c=l(',x:{x}.union(*[{u(int("1"*a)*x)}|{T(u,f,X,Y)for j in r(1,a)for X in c(j,x)for Y in c(a-j,x)for f in[l(",b:a%sb"%o)for o in{"**"}|set("+-*/")]+[l(",b:a**b**-1")]}for u in[l(":-a")]+[l(":a**.5**%i"%k)for k in r(9)]])')
R=l(",i:[{n+1}<c(i,a)for n in r(10)]")

```

Here is a rather ungolfed version:

```
def R(x,i):
    # Unary Operations
    U = [lambda a:-a] + [eval("lambda a:a**(1/2.**%i)" % j) for j in range(9)]
    # Binary Operations
    F = [eval("lambda a,b:a%sb"%o) for o in ["+","-","*","/","**"]] + [lambda a,b:a**(1./b)]

    def combos(i):
        L = {x}
        for u in U:
            # 3, 33, 333, etc.
            L |= {u(int(str(x)*i))}

            for j in range(1,i):
                for X in combos(j):
                    for Y in combos(i-j):
                        for f in F:
                            # To avoid trouble with division by zero, overflows and similar:
                            try:
                                L |= {u(f(X,Y))}
                            except:
                                pass
        return L

    return [n in combos(i) for n in range(1,11)]

```

For testing I recommend to change `(9)` to something smaller, since this is the number of multiple square roots taken into account, which has a huge impact on the performance.

Finally, this made me wonder, whether the unary minus is actually needed in some case …

# Answer
> 2 votes
### Mathematica - 246 characters (no bonuses claimed)

```
f[x_,y_]:=x-y
g[x_,y_]:=x/y
h[x_,y_]:=x^(1/y)
j[x_,y_]:=FromDigits@Join[IntegerDigits@x,{y}]
z[{r_,n_,L_}]:=z[{L[[1]][r,n],n,Rest@L}]
z[{r_,n_,{}}]:=r
a[n_,t_]:=Union@Select[z[{n,n,#}]&/@Tuples[{Plus,f,Times,g,Power,h,j},t-1],IntegerQ@#&&0<#<11&]

```

### Explanation

Function `j` concatenates two numbers digit-wise.

Function `z` takes a result `r`, number `n`, and list of functions `L`, each which operates on two arguments. It then applies the list of functions sequentially to argumnts `[r,n]` using recursion, until the list is empty, whereupon it returns the result.

Function `a` takes a number `n` and a number of copies `t`. It creates all tuples of length (t-1) from the list of functions `{Plus, f, Times, g, Power, h, j}` and sends each tuple through function z, then returns a list of all numbers 1 through 10 that were created.

Example execution `a[2,3]` returning `{1, 2, 3, 6, 8}`.

### Limitations

Because the list of functions is applied sequentially, consuming one copy of the number each time, it can miss some combinations. For example, when operating on four twos, it would miss 22/22 = 1 due to its inability to evaluate the list of functions out of order. Of course, 2/2\*2/2 = 1 covers this case.

---
Tags: code-golf, math, arithmetic, expression-building
---


# Question
Title: Monkey Island: The Head of the Navigator
**Warning:** This challenge contains some mild spoilers for The Secret of Monkey Island.

Towards the end of the game, you're being led through the catacombs by a magically preserved head of a navigator:

You need its eyeball necklace, but the Head is reluctant to give it to you. One way to get it is just to keep begging:

> **Guybrush:** May I please have that necklace?
> **Head:** No, but thanks for asking so politely.
> **Guybrush:** Oh come on, pleeeeease?
> **Head:** You can beg all you want, but you can't have it.
> **Guybrush:** Pretty please?
> **Head:** You can beg all you want, but you can't have it.
> **Guybrush:** Pretty PRETTY please?
> **Head:** You can beg all you want, but you can't have it.
> **Guybrush:** Pretty please with sugar on top?
> **Head:** Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?

## The Challenge

Write a full program which prints the above dialogue. The catch is that each time the program is called it should only print two lines (one pleading by Guybrush and the Head's response). E.g. if your submission is written in Python, usage should look like this:

```
$> python please.py
Guybrush: May I please have that necklace?
Head: No, but thanks for asking so politely.
$> python please.py
Guybrush: Oh come on, pleeeeease?
Head: You can beg all you want, but you can't have it.
$> python please.py
Guybrush: Pretty please?
Head: You can beg all you want, but you can't have it.
$> python please.py
Guybrush: Pretty PRETTY please?
Head: You can beg all you want, but you can't have it.
$> python please.py
Guybrush: Pretty please with sugar on top?
Head: Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?

```

Invoking the program more than 5 times may result in undefined behaviour, so you could either loop, keep printing the last two lines or the program could even be broken after the 5th invocation.

You may write to a file in the working directory, or you can modify the source code of the program itself to keep track of invocations. In the latter case, your program must not depend its own filename. (In the former case, you can assume that your program's file name will not clash with any file names your program depends on.)

You must not assume a REPL-like environment or that any data is kept in RAM between invocations. E.g. if you answer in Mathematica, you have to assume that I quit the kernel between invocations.

This is code golf, the shortest answer (in bytes) wins. If your program depends on any additional files to exist *before the first invocation*, add its name and contents to your byte count.

# Answer
> 9 votes
# Python, 224 + 97 + 1 = 322 characters

A most straightforward solution to start us all off. Thanks to gnibbler for helping me shave off 18 bytes!

```
n=0
print open('z','rb').read().decode('zip').split('|')[n]
open(__file__,'r+').write("n="+`n+1`)

```

Requires the file `z` to be present in the same directory (+1 for filename, +224 for file size):

```
$ hexdump z
0000000 9c78 d1ad 6e3d 30c3 050c bde0 78a7 165b
0000010 0723 92c8 48a9 b43a 8209 192c 9b29 0491
0000020 a2ab 9fa1 021a f87a 715a f46c d100 1026
0000030 1efc 1e41 5172 4721 c3b3 1527 607c 4c70
0000040 6191 87e8 0c91 7825 7b6e 2d47 dfef 4c8e
0000050 0edd d25f e540 8b54 8fbe 4bb8 c500 7ade
0000060 288d c418 c4d9 6cae 0f7f 7bab 6832 9be5
0000070 be21 7aa9 537d c2c2 24dd 25a3 c50f e41a
0000080 ca1c 1ff4 a7c9 a439 d5cc 9a4d b207 3fe9
0000090 0e7c 529c 4e79 3afc 7cef bf79 6f5e 672f
00000a0 8b9f 6d1d 8832 5359 1698 2482 92c3 3270
00000b0 43cd 560e 899b a4ad 1ab2 548a aed9 0bf1
00000c0 238f 0697 bd63 168f 36e9 b411 0a1e fef6
00000d0 eee8 1d64 1a28 aec9 10e3 7ff7 3a0b d9ab
00000e0

$ ls -l z
-rw-r--r--+ 1 Laxori mkpasswd 224 2014-09-22 22:35 z

```

You can generate `z` with the following:

```
>>> open('z','wb').write("""eJyt0T1uwzAMBeC9p3hbFiMHyJKpSDq0CYIsGSmbkQSroqGfGgJ6+FpxbPQA0SYQ/B5BHnJRIUez
wycVfGBwTJFh6IeRDCV4bntHLe/fjkzdDl/SQOVUi76PuEsAxd56jSgYxNnErmx/D6t7MmjlmyG+
qXp9U8LC3SSjJQ/FGuQcyvQfyac5pMzVTZoHsuk/fA6cUnlO/DrvfHm/Xm8vZ5+LHW0yiFlTmBaC
JMOScDLNQw5Wm4mtpLIailTZrvELjyOXBmO9jxbpNhG0Hgr2/ujuZB0oGsmu4xD3fws6q9k=""".decode('base64'))

```

Output:

```
$ python monkeyisland.py
Guybrush: May I please have that necklace?
Head: No, but thanks for asking so politely.
$ python monkeyisland.py
Guybrush: Oh come on, pleeeeease?
Head: You can beg all you want, but you can't have it.
$ python monkeyisland.py
Guybrush: Pretty please?
Head: You can beg all you want, but you can't have it.
$ python monkeyisland.py
Guybrush: Pretty PRETTY please?
Head: You can beg all you want, but you can't have it.
$ python monkeyisland.py
Guybrush: Pretty please with sugar on top?
Head: Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?
$ python monkeyisland.py
Traceback (most recent call last):
  File "monkeyisland.py", line 2, in <module>
    print open('z','rb').read().decode('zip').split('|')[n]
IndexError: list index out of range

```

# Answer
> 5 votes
**Common Lisp (SBCL) : 659 characters**

```
(defparameter *d*
  '#1=("~A May I please have that necklace?"
       "~A No, but thanks for asking so politely."
       "~A Oh come on, pleeeeease?"
       #2="~A You can beg all you want, but you can't have it."
       "~A Pretty please?"
       #2#
       "~A Pretty PRETTY please?"
       #2#
       "~A Pretty please with sugar on top?"
       "~A Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?" . #1#))
(defun d ()
  (format t (pop *d*) "Guybrush:") (terpri)
  (format t (pop *d*) "Head:") (terpri)
  (terpri)
  (finish-output)
  (sb-ext:save-lisp-and-die "please" :toplevel 'd :executable t))
(d)

```

# Explanations

* I dump the lisp image after each invocation, which saves current state.
* The circular list let me restart the dialogue after all lines have been displayed (not required, but at least it doesn't error on `format` with `nil`).
* Reader macros allow me to reuse some identical lines.

This won't be the shortest submission, but I thought this was a nice approach to the problem.

# Firt invocation

```
 $sbcl --noinform --noprint --load please.lisp
 Guybrush: May I please have that necklace?
 Head: No, but thanks for asking so politely.

 [undoing binding stack and other enclosing state... done]
 [saving current Lisp image into please:
 writing 5856 bytes from the read-only space at 0x0x20000000
 writing 4032 bytes from the static space at 0x0x20100000
 writing 67960832 bytes from the dynamic space at 0x0x1000000000
 done]

```

# Subsequent invocations

```
$./please
Guybrush: Oh come on, pleeeeease?
Head: You can beg all you want, but you can't have it.

[undoing binding stack and other enclosing state... done]
[saving current Lisp image into please:
writing 5856 bytes from the read-only space at 0x0x20000000
writing 4032 bytes from the static space at 0x0x20100000
writing 68091904 bytes from the dynamic space at 0x0x1000000000
done]

$./please
Guybrush: Pretty please?
Head: You can beg all you want, but you can't have it.

[undoing binding stack and other enclosing state... done]
[saving current Lisp image into please:
writing 5856 bytes from the read-only space at 0x0x20000000
writing 4032 bytes from the static space at 0x0x20100000
writing 68091904 bytes from the dynamic space at 0x0x1000000000
done]

```

# Answer
> 3 votes
## C# - 593 + 1 + 1 Characters (595)

*Edits: Updated with suggestions from Martin and various other optimisations*

First +1 is a filename. Second +1 is contents of that file. Without all the spaces and line breaks removed so you can read it:

```
using System.IO;
using s=System.String;
class P
{
    static void Main()
    {
        s g="Guybrush: ",h="Head: ",p=" please",q="Pretty";
        s[]b=new s[]{"May I"+p+" have that necklace","No, but thanks for asking so politely.",
        "Oh come on, pleeeeease","You can beg all you want, but you can't have it.",q+p,
        "Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?",
        q+" PRETTY"+p,"",q+p+" with sugar on top"};
        int a=int.Parse(File.ReadAllText("x",System.Text.Encoding.UTF8));
        System.Console.WriteLine(g+b[a]+"?\n"+h+b[(a+5)/6*2+1]);
        File.WriteAllText("x",(a+2).ToString());
    }
}

```

**Explanation**

Relies on a text file called "x" to be present in the directory. Should initially contain a zero and is used to store progress.

Program plucks relevant element out of the string array according to progress and writes progress at end. Some lines reused to shorten length, hence index selection logic `h+b[(a+5)/6*2+1]` for answer selection.

**Output**

```
D:\Projects\Junk\MI\bin\Debug>MI
Guybrush: May I please have that necklace?
Head: No, but thanks for asking so politely.

D:\Projects\Junk\MI\bin\Debug>MI
Guybrush: Oh come on, pleeeeease?
Head: You can beg all you want, but you can't have it.

D:\Projects\Junk\MI\bin\Debug>MI
Guybrush: Pretty please?
Head: You can beg all you want, but you can't have it.

D:\Projects\Junk\MI\bin\Debug>MI
Guybrush: Pretty PRETTY please?
Head: You can beg all you want, but you can't have it.

D:\Projects\Junk\MI\bin\Debug>MI
Guybrush: Pretty please with sugar on top?
Head: Oh, all right, you big baby. You can have it. Hey, what good's a necklace
if you don't have shoulders?

D:\Projects\Junk\MI\bin\Debug>

```

My first code golf, probably not the shortest possible in C# but hey - Monkey Island, couldn't resist!

Stripped code:

```
using System.IO;using s=System.String;class P{static void Main(){s g="Guybrush: ",h="Head: ",p=" please",q="Pretty";s[]b=new s[]{"May I"+p+" have that necklace","No, but thanks for asking so politely.","Oh come on, pleeeeease","You can beg all you want, but you can't have it.",q+p,"Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?",q+" PRETTY"+p,"",q+p+" with sugar on top"};int a=int.Parse(File.ReadAllText("x",System.Text.Encoding.UTF8));System.Console.WriteLine(g+b[a]+"?\n"+h+b[(a+5)/6*2+1]);File.WriteAllText("x",(a+2).ToString());}}

```

# Answer
> 3 votes
## JS, ~~488~~ 473

Refreshing 5 times the page containing this code displays the 5 different dialogs.

```
l=localStorage;a="<p>Guybrush: ";b=a+"Pretty please";d="<br>Head: ";c=d+"You can beg all you want, but you can't have it.";document.write(a+"May I please have that necklace?"+d+"No, but thanks for asking so politely."+a+"Oh come on, pleeeeease?"+c+b+"?"+c+a+"Pretty PRETTY please?"+c+b+" with sugar on top?"+d+"Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?<style>p:not(:nth-child("+(l[0]=~~l[0]+1)+")){display:none")

```

Demo:

http://c99.nl/f/212197.html

# Answer
> 2 votes
## Perl - 356 bytes

```
2=~//;@d=qw"No6|thanks|for|asking|so|pol8ely. 5|beg72want62can't18.
Oh,7|right,2big|baby.|518.|Hey,|what|good's|a4|if2don't1shoulders?
May|I01that4 Oh|come|on,|pleeeeease 30 3|PRETTY0
30|w8h|sugar|on|top";print"Guybrush: $d[$'+print F$'+sysopen F,$0,1]?
Head: $d[$'/3]"=~s/\d/qw(|please |have| |you| Pretty |necklace You|can
,|but |all it)[$&]/ger=~y/|/ /r

```

A self-modifying approach, with substitutions for common strings.

Sample Usage:

```
$ perl please.pl
Guybrush: May I please have that necklace?
Head: No, but thanks for asking so politely.

$ perl please.pl
Guybrush: Oh come on, pleeeeease?
Head: You can beg all you want, but you can't have it.

$ perl please.pl
Guybrush: Pretty please?
Head: You can beg all you want, but you can't have it.

$ perl please.pl
Guybrush: Pretty PRETTY please?
Head: You can beg all you want, but you can't have it.

$ perl please.pl
Guybrush: Pretty please with sugar on top?
Head: Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?

```

---
Tags: code-golf, kolmogorov-complexity, stateful
---


title: multiplication table in javascript

text:
# Question
Title: 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?

# Answer
## 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)
> 4 votes

---
Tags: code-golf, tips, javascript
---


title: Help me with trigonometry!

text:
# Question
Title: Help me with trigonometry!
Thank you guys so much for your help with calculus. Now I need some help with my upcoming trigonometry test.

On the test, I'll need to simplify expressions. I’ll be given input like `4sin(x)/(2cos(x))` and will have to produce a simpler, but equivalent expression (such as `2tan(x)`). All angles are in degrees, and we'll pretend there are no division-by-zero or invalid-domain issues. (For example, we'll assume that tan(x+1)cot(x+1)sin(x)/sin(x) is always 1.)

I snuck into the professor's office, and got a list of 100 problems that might be on the test. Please give me teh code to solve them all. It’s possible that some of the problems are already simplified as much as possible; if so just give back the input.

I need expressions to be simplified, but I also want a short program (or function) so the professor won't notice. **Try to minimize the sum of the program’s length and the total length of all of the solutions.**

Just to clarify, it's okay if some of the expressions are returned unchanged, or even returned in an equivalent but longer form. Also, the program only needs to work on the expressions listed below; it can return incorrect results or even break for other inputs.

As you can tell, all of the problems follow a similar format. `x` is the only variable used, there are no spaces, and parentheses follow each function name. (The functions are `sin`, `cos`, `tan`, `sec`, `csc`, and `tan`.) There are no nested functions, but inside a function may be an expression like `3x+4.5` or `-2-.7x`. Exponents may be used, but only on functions (e.g. `sin(x-.5)^7`), and the power is always a integer above one. Multiplication is indicated through concatenation.

The outputs will need to be in this format as well. Invalid: `sin x`, `sin(x)/cos(x)tan(x)` \[is the tangent multiplied or divided?\], `cos(x` \[close all parentheses\], `4*sin(x)`, `sec(x)^1`

I can use any programming language, unless it relies on built-in simplification or expression-handling functions. Built-in trig functions are okay. (I'll have a very basic scientific calculator during the test.) Also, since I'll be reading the program written on paper, I can only use printable ASCII characters (0x20 through 0x7E) and newlines.

```
1/(sec(x))
4+sin(x)+3
(cos(7x+4)-sin(-3x))/(sin(-3x))
2sin(x)2tan(x).25cos(x)^3cos(x)+1+1
7cos(x)sec(x)/(14tan(x)csc(x))
sin(x)cos(x)/sec(x)
8sin(x)cos(x)sin(x)/tan(x)+8sin(x)
sin(x)^9cos(x)cot(x)sec(x)csc(x)sec(x)tan(x)/(cot(x)^2tan(x)cos(x)^4cot(x)sin(x))
tan(x)cos(x)csc(x)
tan(x+1)sin(x-1)cos(x+1)^3tan(x-1)^2sin(-x+1)csc(x+1)tan(-x+1)/(cos(x-1)cot(x+1))
(cos(2x)+cot(2x)-sin(2x)+csc(2x)^3)/(cot(2x)+sin(2x))
cos(90-x)cos(x)
sin(x+180)sec(450-x)
tan(-x)sin(x+90)sec(x-90)
tan(x+180)^2
cot(-x)cos(-x)
cot(180-x)^3cos(270-x)^2
sin(.1x-.2)sin(.1x-.2)sin(.1x-.2)sin(.2-.1x)sin(.2-.1x)
sin(x)
sin(90-x)sin(x)+cos(90-x)/sec(x)
tan(3x+2)cos(3x+2)/sin(3x+2)-1
cos(x)cos(x)cos(x)cos(x)cos(x)
sec(2x+1)sec(-1-2x)+sec(-2x-1)sec(2x+1)
cos(4x)cot(4x)tan(4x)sin(4x)csc(4x)
-cos(x)+cos(x)+sin(2x-4)-1/csc(2x-4)
sec(x)sec(x+2)cot(x)tan(x-2)tan(x+180)
tan(x)(tan(x))
3sin(x)sin(x)/(3)
cos(x)sin(x)
tan(x)sec(x)^2
tan(x)^2-sec(x)^2
7+sin(x)csc(x)csc(x)+cot(x)^2
sin(90)+cos(-90)+sec(180)
csc(1)+csc(10)-csc(30)-csc(60)+csc(90)
sin(36000001)
csc(800)+(cot(720+x)-sec(4x-720))
sin(-x)+sin(x)
csc(-x)+csc(x)
4sin(x)-sin(x)+tan(x)-2tan(x)
cot(x)+10cot(x+90)+99cot(x+180)+.01cot(x-90)
tan(x)tan(x+180)
sec(x)sin(x+180)tan(x-270)cot(x-450)csc(x+90)
sin(x)/cot(x)+sin(x)/cot(x)
sin(x)csc(x)+tan(x)cot(x)+cos(x)sec(x)
cot(x)
9tan(x+90)+90tan(x+9)
cos(x-9999)+tan(x+99999)
2tan(x)tan(x)/2
tan(x)/tan(x-360)+cos(x+180)/cos(x)
csc(4x)sec(270-4x)
cot(91+x)tan(x-449)
csc(2x)(csc(2x)-sin(2x))
csc(x+1)^2-cot(x+1)cot(x+1)
cot(x)cot(x)+1
tan(x)^2-sec(x)sec(x)
tan(x)/cot(x)+csc(x)/csc(x)
cot(x)sin(x)/cos(x)
csc(x)tan(x)cos(x)
csc(x)cot(x)cos(x)
csc(x+90)csc(-x+270)-1
cot(x)/cot(x)+tan(x)/cot(x)+cot(x)cot(x)
sec(x)sec(x)sec(x)sec(x+90)sec(x-90)sec(x+180)
1-cos(x)cos(x+180)+sin(x)^2
sec(x)sec(x)sec(x)sec(x)/cos(x)+cot(x)
cot(x+1)csc(x-1)sec(x+1)tan(x-1)sin(x+1)cos(x-1)
sin(x)-cos(x)+tan(x)-sec(x)+cos(x)-csc(x)
tan(x+23515)-sec(-.27x-23456)
sec(-.9x)
-tan(-x)-csc(360-x)
cos(-x)sec(x)sin(x)csc(-x)
tan(-x)^2-sin(-x)/sin(x)
tan(x)tan(x)+1
csc(x)^2-1
cot(2x)cot(2x)-csc(2x)/sin(2x)
2sec(x)/(6cos(x))
sec(0)+tan(30)cos(60)-csc(90)sin(120)cot(150)+tan(180)csc(210)sin(240)-cos(270)sec(300)+cot(330)
tan(x-1234567)sec(4781053+x)^2
tan(-1234567x)sec(4781053x)^2
sin(x)^9+cos(x)^7+csc(x)^5-cot(x)^3
cos(-33x-7.7)
sec(-.1-x)+tan(-2x-77)
tan(x)+sin(x)-cos(x)+tan(x)-sin(x)
cos(x)-sec(x)/tan(x)+tan(x)/sin(x)
cot(x)-cos(x)/sin(x)
3cos(x)+2/sec(x)-10sin(x)/(2tan(x))
tan(x+3)^11+sin(x+3)^8-cos(x+3)^5+5
sec(x)+sec(x)
csc(.1x)csc(-.1x)csc(x)
cot(x-7)cot(x-7)cot(x+173)cot(x-7)cot(x+173)cot(x-367)
cos(.0001x+1234567)
cot(45)+tan(225)-sin(210)+cos(-60)
sin(12345)cos(23456)tan(34567)sec(45678)csc(56789)cot(67890)
cos(1234x)+cot(1234)+tan(1234x)+sec(1234)+csc(1234)+sin(1234x)
sec(x)sec(x)sec(x)sec(x)sec(x)sec(x)
csc(x)cot(x)sec(x)csc(x)tan(x)sec(x)cot(x)csc(x)cot(x)cos(x)cos(x)cot(x)sin(x)sin(x)cot(x)
csc(2553273)+cot(1507348)-sec(5518930)+csc(5215523)+tan(3471985)-sec(4985147)
sin(20x)+cos(20x)-tan(20x)+sin(20x)-csc(20x)+cot(20x)-tan(20x)+csc(20x)
cot(100000)+cot(100000x)+cot(100000x)+cot(100000)
csc(5x+777)sin(5x+777)
csc(4.5x)

```

*Note: This scenario is entirely fictional. In real life, cheating and helping others cheat is wrong and should never be done.*

# Answer
# Python, 436 + 1909 = 2345

This must be one of the most inefficient solutions imaginable and mathematicians will probably cringe, but I've managed to throw something together that actually simplifies about half of the expressions without any hardcoding:

```
from math import*
import exrex,re
d=lambda f:lambda x:f(x*pi/180)
sin,cos,tan=d(sin),d(cos),d(tan)
i=lambda f:lambda x:1/f(x)
sec,csc,cot=i(cos),i(sin),i(tan)
t=lambda s:[round(eval(re.sub('([\d\).])([\(a-z])','\\1*\\2',s).replace('^','**')+'+0')*1e9)for x in[1,44]]
def f(I):
 try:return min((s for s in exrex.generate('(-?\d|\(1/\d\.\))?([+-]?(sin|cos|tan|cot|sec|csc)\(x\)(\^\d)?){0,4}')if s and t(s)==t(I)),key=len)
 except:return I

```

The output for the 100 test cases should be the following (where `#` marks expressions that were not simplified):

```
cos(x)
7+sin(x)
#
2+tan(x)^2cos(x)^2
(1/2.)cos(x)
sin(x)cos(x)^2
#
sin(x)^2tan(x)^7
1
#
#
sin(x)cos(x)
-1
-1
tan(x)^2
-cot(x)cos(x)
-cot(x)cos(x)^2
#
sin(x)
2sin(x)cos(x)
0
cos(x)^5
#
#
#
#
tan(x)^2
sin(x)^2
sin(x)cos(x)
tan(x)sec(x)^2
-1
7+cot(x)^2+csc(x)
0
#
#
#
0
0
3sin(x)-tan(x)
#
tan(x)^2
-tan(x)sec(x)
2sin(x)tan(x)
3
cot(x)
#
#
tan(x)^2
0
#
1
#
1
csc(x)^2
-1
sec(x)^2
1
1
cot(x)^2
-1-sec(x)^2
cot(x)^2+sec(x)^2
sec(x)^4csc(x)^2
2
cot(x)+sec(x)^5
#
sin(x)+tan(x)-csc(x)-sec(x)
#
#
tan(x)+csc(x)
-1
sec(x)^2
sec(x)^2
cot(x)^2
-1
(1/3.)sec(x)^2
#
#
#
#
#
#
2tan(x)-cos(x)
cos(x)-csc(x)+sec(x)
0
0
#
2sec(x)
#
#
#
3
#
#
sec(x)^6
cot(x)^4csc(x)
#
#
#
1
#

```

The idea is quite simple:

* generate a huge amount of possible expressions
* select those that yield the same result as the expression you want to simplify, comparing them for some (here two) x values
* from the equivalent expressions return the shortest one

The problem is that there are quite a lot of possible expressions to check, so I limited it to a subset.

To be honest I was not patient enough to test the golfed code above. (Tell me if you think that's cheating.) Instead I used a much longer but more efficient rule to generate an even smaller subset of expressions that hopefully still contains all the desired simplifications. Should you want to try that, replace the regular expression in the second to last line of the code with the following (and be prepared for a few minutes of computation time):

```
'0|((-1|\(1/[23]\.\)|[1237])[+-]?)?(sin\(x\)(\^2)?)?-?(tan\(x\)(\^[27])?)?(cot\(x\)(\^[24])?)?[+-]?(cos\(x\)(\^[25])?)?(sec\(x\)(\^[2456])?)?(csc\(x\)(\^2)?)?'

```

The program also contains quite some overhead that was needed to make Python understand the mathematical expressions. This involved

* redefining `sin`,`cos`and `tan` to take arguments in degrees instead of radiens (which is what I think the OP intended)
* defining `sec`,`csc` and `cot` which are not part of the `math` package
* inserting all the implied multiplication signs
* replacing the exponentiation operator
> 8 votes

# Answer
## CJam, 1 + 3000 = 3001

Just as the baseline solution to give people something to beat:

```
l

```

This reads STDIN onto the stack, whose contents are printed at the end of the program.

I'm sure this can be beaten, but I'm also sure that many optimisations can't be implemented in the characters that would be gained.
> 6 votes

# Answer
# Javascript (438 + 2498 = 2936)

The object in the middle optionally contains simplified outputs based on the length of the input and the first character. Otherwise, the input is returned unmodified.

```
s='sin(x)';(p=prompt)({
    352:s+"^2cos(x)^3+2",
    307:"cos(x)/2",
    348:s+"8(1+cos(x)^2)",
    "81s":s+"^2tan(x)^7",
    "55s":"-sin(0.2-0.1x)^5",
    "39s":"2sec(2x+1)^2",
    "35c":"cos(4x)",
    "36-":0,
    173:s+"^2",
    "25s":0,
    294:s+"3-tan(x)",
    "27s":s+"2/cot(x)",
    "40c":"1+tan(x)^2+cot(x)^2",
    "48c":1,
    "41s":s+"+tan(x)-csc(x)-sec(x)",
    "26c":-1,
    "24t":"1+tan(x)^2",
    "96s":"2.5+1/cos(30)",
    "34t":"2tan(x)-cos(x)",
    353:0,
    "36s":"6sec(x)",
    "90s":"cot(x)^4csc(x)"
}[(i=p()).length+i[0]]||i)

```

The whitespace is just for decoration and not included in the character count.

It's a shame that adding all these solutions only saved me a few characters, but better than nothing. The simplification was done via wolframalpha – I'll just trust it.
> 5 votes

---
Tags: code-challenge, math, kolmogorov-complexity, trigonometry
---


# Question
Title: Program a 2048 AI using an existing Framework
> **EDIT : Recently, my question has been proposed as a duplicate of 2048 Bot Challenge. I would like to stress that this question is different from that question, and will require answers to be thought of differently than that question. 2048 Bot Challenge asked the user to create a bot, and it would be run for an hour, with the highest score being the user's score. Additionally, it had a limit of 555 bytes. My challenge runs the code much less frequently, only 3 times. Your score is calculated by using the average score of those three times and dividing by the character length of your golfed code. My question encourages entries to be "smarter," and not try and get the highest score by brute force.**

-

> EDIT: The get method was changed to getTile, to avoid confliction with the JS keyword get. Additionally, a high score section was added.

Recently, I created a site that allows the popular game 2048 to be controlled using JavaScript. My site is linked here:

http://thatcoolidea.com/2048

How:

An Ace Editor is located above the board. You place code in it, which is run once every 250 ms, or 4 times per second. This is called a cycle.

Use the following methods to control the board. You can't use the arrow keys.

```
up();            //move up
down();          //move down
left();          //move left
right();         //move right

move(integer);   //integer is a direction. 0:up,1:right,2:down,3:left

getTile(y,x);        //gets the value of the tile in position y,x on the board. See diagram

```

The following variables are defined for your convenience:

```
eother        //boolean, alternates every cycle
frozen        //integer, counts how many cycles the board has remained stationary
lastDir       //integer, indicates the last direction that was tried to move in
              //uses same format as the move method above.
startup       //boolean, will always be true when the game first starts
              //you can change it as you wish
a
b             //a b and c are all persistant variables, they do not change each cycle
c             //any other variables defined in the cycle will be reset every time

```

Rules:

* No Randomness, you must use logic. (Yes, I know the example code uses random.)
* No hooking into the game functions or cheating in other ways
* Generally, try to only call one move method per cycle. It is OK if you use more, but it screws with the animation
* The board must start in a random state, no modification of pre-game state
* You must provide both the uncompressed and golfed version of the code in your post.
* You must provide a link to the site that already loads the uncompressed version of your code, served via PasteBin (For example, ...thatcoolidea.com/2048?i=pH18GWtu loads the example code.)

Scoring:

* Your code will be scored by me.
* Part A of your score is an average of 3 runs of the code, rounded down.
* Part B of your score is the character length of your golfed code.
* Your final score is Part A divided by Part B

The winner will have their code immortalized as the example code on the site, if they choose, and acknowledged in a comment in the code.

Good luck! Hope you enjoy the challenge.

**Current High Score** 225.22 - Freezer - user3217109

# Answer
> 6 votes
# Sinker/Shaker, 65 bytes

Here's mine. It's as blind and simple as they come.

```
if(startup){startup=false;a=0}b=(a++)%4;move(frozen>2?0:b==0?2:b)

```

Uncompressed(ish)...

```
if(startup){startup=false;a=0;}
b=(a++)%4;
move(frozen>2?0:b==0?2:b)

```

All it does is repeats down, right, down, left, etc. and hits up once if it gets stuck. It doesn't always do very well, but it'll occasionally get 512s. My high score during testing was 7520.

# Answer
> 3 votes
# Traffic light - 23 21 bytes

```
move(frozen&2|eother)

```

This is the link.

This will move alternatingly up and right, except when the board has remained stationary for the last two moves, in which case it will move down and left respectively.

My original, functionally equivalent submission was 23 bytes long and scored 182.72:

```
move((frozen&2)+eother)

```

# Answer
> 2 votes
# Whirlpool - 37 21 17 bytes - Score: 211.22

I decided to go with a "less is more" approach. My code is a simple design that tries to go up, right, down, left... I will be working on a learning AI to see a more optimal way to approach the puzzle.

```
a=a|0;move(a++%4)

```

Optimizer helped to shorten `a`'s initialization.

Sam helped to shorten `a`'s initialization, removed `var`.

Ungolfed?

```
var a=a|0;
a++;
move(a%4);

```

My top score with this AI is 5120.

# Freezer - 12 bytes - Score: 225.22

This bot has move priority. It attempts to go up. If it can' go up, it goes right. If it can't go right, it does down. If it can't go down it goes left.

```
move(frozen)

```

## James Bond Explanation

The encrypted code decrypts to say:

```
HTMLActuator.prototype.updateScore=function (score) {score*=9989800000;
  this.clearContainer(this.scoreContainer);

  var difference = score - this.score;
  this.score = score;

  this.scoreContainer.textContent = this.score;

  if (difference > 0) {
    var addition = document.createElement("div");
    addition.classList.add("score-addition");
    addition.textContent = "+" + difference;

    this.scoreContainer.appendChild(addition);
  }
}

```

Optimizer should have golfed his decrypted code. This could have been #Optimized.

# Answer
> 1 votes
# Hanger - 20 bytes

### Official score: 224.87 - 2nd place by 0.35 points

This bot uses the down, left, down, right approach, but with the unusual feature that it will never move up. I'm not sure how to score cases where it hangs and does not complete, or whether the fact that that occurs renders it illegal. Here it is, though:

```
b=b|0;move(b++%4||2)
OR
move(startup++%4||2)

```

Initialization pattern thanks to @Optimizer.

In my 3 test runs, it scored 4284, 6352 and 4232, for an average of 4956. I will update when the official test is run.

---

Alternate version which gets out of hangs (27 bytes):

```
b=b|0;move(b++%4||b%997&&2)

```

---
Tags: code-challenge, game, javascript, ai-player, sliding-puzzle
---


title: Convert number bases

text:
# Question
Title: 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

```

# Answer
> 1 votes
# 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

```

# Answer
> 1 votes
## 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 `⍵⍵`.

# Answer
> 0 votes
## CJam, 20 bytes

```
rr:Ff#F,bAbsr:Tf#T,b

```

Input is like:

```
ee fecdba9876543210 9876543210

```

Output:

```
82

```

Try it online here

---
Tags: code-golf, math
---


title: The distance between circles

text:
# Question
Title: The distance between circles
Imagine you are given two lists of numbers which are to be interpreted as points on a circle of circumference 1000. Let us say

```
circleA = [10, 24, 44, 175, 321, 579, 618, 841, 871, 979]
circleB = [270, 283, 389, 406, 435, 457, 612, 684, 692, 732]

```

To measure the distance between these two circles we do the following.

For the first point in circleA, starting from the left, we find the next biggest point in circleB. So 10 finds 270 and is matched up with it. Now, using 270, we skip to the next biggest point in circle A which is 321. We then use 321 to find 389 and match up 321 and 389 and repeat until the end of circleA or we can't find a matching pair.

This gives us a list of pairs as follows.

```
[(10,270), (321, 389), (579,612), (618,684)]

```

We say the distance between circleA and circleB is just the average difference between pairs. That is (270-10 + 389-321+612-579+684-618)/4 = 106.75

Now comes the tricky part. As the point are on a circle, we can rotate circleB and recompute this distance. The task is to compute the following value.

> For arbitrary inputs circleA and circleB, the task is to compute the average distance between circleA and all rotations of circleB.

In order to make it interesting I am setting this as fastest-code challenge. I will test with increasing size circles created using (in python)

```
import random
circumference = 1024
numberpoints = circumference/64
circleA = sorted(random.sample(range(circumference),numberpoints))
circleB = sorted(random.sample(range(circumference),numberpoints))

```

I will just double the size of circumference until the code takes more than 1 minute to run on my computer. You output should be accurate to machine precision.

Please provide full instructions for how to compile and run your code on a linux machine.

---

A rotation simply means adding an offset modulo `circumference` and then resorting. In python

```
rotatedcircleB = sorted([(c+offset)%circumference for c in circleB])

```

# Answer
This algorithm is basically the same as @fredtantini's. The main difference is I keep a rolling sum instead of creating a list to hold the differences. I also forgo the list slicing as it is **an O(k) operation**.

```
from __future__ import division
from bisect import bisect_left
import timeit

def circular_distance(circle_a, circle_b):
    total = 0
    count = 0
    value_on_a = circle_a[0]
    value_on_b = 0
    while 1:
        try:
            insertion_point = bisect_left(circle_b, value_on_a)
            value_on_b = circle_b[insertion_point]

            total += value_on_b - value_on_a
            count += 1

            value_on_a = circle_a[bisect_left(circle_a, value_on_b+1)]
        except IndexError:
            break
    return total/count

def rotate(circle, offset, circumference=1024):
    return sorted((point + offset) % circumference for point in circle)

def get_average_distance(circle_a, circle_b, circumference=1024):
    total = 0
    for iteration_num in xrange(circumference):
        total += circular_distance(circle_a, rotate(circle_b, iteration_num))
    return total/circumference

```

These changes resulted in about a 64% improvement for 10,000 iterations on my machine:

```
                     +------------------+-------------------------+
                     | List and slicing | Rolling sum and average |
+--------------------+------------------+-------------------------+
| Per Iteration (ms) |  0.0128661600274 |    0.00821646809725     |
+--------------------+------------------+-------------------------+
|          Total (s) |    128.661600274 |       82.1646809725     |
+--------------------+------------------+-------------------------+

```
> 1 votes

# Answer
My first try at a `fatest-code` question. Problem is, I didn't try any optimization…

If the rotation part isn't correct, please tell me.

Also, I don't know how to time test the code, so I tried to use `timeit` module to run 1000 times in order to have a correct timing. I am not sure if I have to do that, or if it is your part :þ

Anyway, here is my code:

```
import random
circumference = 1024
numberpoints = circumference/64
circleA = sorted(random.sample(range(circumference),numberpoints))
circleB = sorted(random.sample(range(circumference),numberpoints))

####
from  bisect import bisect_left

def find_next(a, x):
    i = bisect_left(a, x)
    if i != len(a):
        return i, a[i]
    raise ValueError

def dist1(cA, cB):
    l = []
    p = cA[0]
    cA = cA[1:]
    while True:
        try:
            (i, n) = find_next(cB, p)
            l.append(n-p)
            cB = cB[(i+1):]
            (i, p) = find_next(cA, n)
            cA = cA[(i+1):]
        except:
            break
    return (sum(l)/len(l))

def rotate(circleB,i):
    return sorted([(c+i)%circumference for c in circleB])

def distAll(circleA, circleB):
    l = [dist1(circleA, rotate(circleB,i)) for i in xrange(circumference)]
    return sum(l)/circumference

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("distAll(circleA,circleB)", setup="from __main__ import *", number=1000))

```
> 1 votes

# Answer
# C

The first argument is a filename which the program expects to read for input. The first line of the file contains the circumference and the number of points each of circle a and circle b. Then the values for circle a follow, one per line; then the values of circle b, one per line.

The time spent reading the input is a huge portion of the overall running time, but I wasn't sure how to get so much input into the program without resorting to file I/O. If anyone has a better solution to that (or any suggestions in general) please feel free to chime in.

Compile it with -O3 for extra speed!

```
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>

static inline void rotateB(int_fast32_t* const, int_fast32_t, int_fast32_t, int_fast32_t);

static inline void getDistances(const int_fast32_t* const, const int_fast32_t* const, int_fast32_t, int_fast32_t, int_fast32_t* const, int_fast32_t* const);

static inline int comparePoints(const void*, const void*);

static inline int_fast32_t getNextIndex(const int_fast32_t* const, int_fast32_t, int_fast32_t, int_fast32_t);

int main(int argc, char* argv[]) {
    int_fast32_t counter;

    int_fast32_t *circleA;
    int_fast32_t *circleB;

    int_fast32_t CIRCUMFERENCE;
    int_fast32_t lengthOfA;
    int_fast32_t lengthOfB;

    FILE *fp = fopen(argv[1], "r");
    fscanf(fp, "%d %d %d\n", &CIRCUMFERENCE, &lengthOfA, &lengthOfB);

    circleA = malloc(sizeof(int_fast32_t)*lengthOfA);
    circleB = malloc(sizeof(int_fast32_t)*lengthOfB);

    for(counter = 0; counter < lengthOfA; counter++)
        fscanf(fp, "%d\n", &(circleA[counter]));
    for(counter = 0; counter < lengthOfB; counter++)
        fscanf(fp, "%d\n", &(circleB[counter]));

    fclose(fp);

    int_fast32_t totalDistance = 0;
    int_fast32_t numberOfPairs = 0;

    for(counter = 0; counter < CIRCUMFERENCE; counter++) {
        rotateB(circleB, counter, lengthOfB, CIRCUMFERENCE);
        getDistances(circleA, circleB, lengthOfA, lengthOfB, &totalDistance, &numberOfPairs);
    }

    printf("%f\n", ((double)totalDistance)/((double)numberOfPairs));

    free(circleA);
    free(circleB);

    return 0;
}

static inline void rotateB(int_fast32_t* const circleB, int_fast32_t offset, int_fast32_t length, int_fast32_t CIRCUMFERENCE) {
    int_fast32_t counter;
    for(counter = 0; counter < length; counter++)
        circleB[counter] = (circleB[counter] + offset) % CIRCUMFERENCE;
    qsort(circleB, length, sizeof(int_fast32_t), comparePoints);
}

static inline int comparePoints(const void* a, const void* b) {
    return (*((int_fast32_t*)a)) - (*((int_fast32_t*)b));
}

static inline void getDistances(const int_fast32_t* const circleA, const int_fast32_t* const circleB, int_fast32_t lengthOfA, int_fast32_t lengthOfB, int_fast32_t* const totalDistance, int_fast32_t* const numberOfPairs) {
    int_fast32_t currentAIndex = 0;
    int_fast32_t currentBIndex = getNextIndex(circleB, circleA[currentAIndex], 0, lengthOfB);
    while((currentAIndex < lengthOfA) && (currentBIndex < lengthOfB)) {
        *totalDistance += circleB[currentBIndex] - circleA[currentAIndex];
        *numberOfPairs += 1;
        currentAIndex = getNextIndex(circleA, circleB[currentBIndex], currentAIndex, lengthOfA);
        currentBIndex = getNextIndex(circleB, circleA[currentAIndex], currentBIndex, lengthOfB);
    }
}

static inline int_fast32_t getNextIndex(const int_fast32_t* const targetCircle, int_fast32_t otherValue, int_fast32_t currentIndex, int_fast32_t length) {
    int_fast32_t lowerBound = currentIndex;
    int_fast32_t upperBound = length-1;
    int_fast32_t guess;
    if(targetCircle[upperBound] <= otherValue)
        return length;
    while(1) {
        if(upperBound - lowerBound < 4) {
            while(targetCircle[lowerBound] <= otherValue)
                lowerBound++;
            return lowerBound;
        }
        guess = (lowerBound + upperBound) >> 1;
        if(targetCircle[guess] > otherValue)
            upperBound = guess;
        else
            lowerBound = guess;
    }
    return lowerBound;
}

```
> 1 votes

---
Tags: math, fastest-code, geometry
---


title: Tangent Polygon Extensions

text:
# Question
Title: 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!

# Answer
> 5 votes
## 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.

# Answer
> 8 votes
# 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"`:

# Answer
> 7 votes
## 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

```

# Answer
> 5 votes
# 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`:

# Answer
> 4 votes
# 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

---
Tags: code-golf, graphical-output
---


title: Spiral Polygons

text:
# Question
Title: Spiral Polygons
Draw a series of connected polygons like the one shown above.

However, what the above picture does not show is the spiral formed by consecutive vertexes:

The limitation of these is that there is only 1 spiral marked. You should mark all the spirals. This can be done by rotating each spiral shown above so that there is a spiral starting at each vertex of the largest polygon.

The spirals should all be one color, while the rest of the picture another.

The innermost polygon should be entirely the color of the spiral.

## Rules

* You will receive the arguments { n, s, p, a } in a function or program
* n = iterations inward (number of polygons)
* s = sides of the (regular) polygon (you may assume n\>=3)
* p = (the linear distance from a vertex of polygon A to its corresponding counter-clockwise "inner" vertex) / (the total length of A's side). So for the diagram, p would be about 1/3 because each inner polygon meets the larger polygon's side at about 1/3 of the way through that side.
* a = the radius (circumscribing) of the exterior polygon

The limit of any of the values of n,s,p or a are based on what can be perceived as this kind of drawing by a human. (e.g. no shaded circles) as well as common sense (s\>=3,n\>=1)

Happy golfing! Shortest program wins.

# Answer
## Mathematica, ~~218~~ 206 bytes

```
{n,s,p,a}=Input[];t=0;Graphics[(c=Array[a{Cos[u=t+2Pi#/s],Sin@u}&,s+1];m=(f=p#2+(1-p)#&)@@c;a=Norm@m;t=ArcTan@@m;k=#;{Line@{#,x=f@##},If[k<n,Red],Line@{x,#2}}&@@@Thread@{c,RotateLeft@c})&~Array~n,Axes->1>0]

```

Expects the input as an array as defined in the question, e.g. `{20, 7, 0.5, 100}`:

or `{20, 5, 0.333, 100}`

These images still use red and grey from an earlier version, but the new version uses black for the counter-clockwise spirals and red for the rest.

I've included an axis, because otherwise the `a` parameter is meaningless with a vector graphic. I've also interpreted `p` as a linear interpolation in position, not in angle.

Ungolfed:

```
{n, s, p, a} = Input[];
t = 0;
Graphics[
 (
    c = Array[a {Cos[u = t + 2 Pi #/s], Sin@u} &, s + 1];
    m = (f = p #2 + (1 - p) # &) @@ c;
    a = Norm@m;
    t = ArcTan @@ m;
    k = #;
    {Line@{#, x = f@##}, If[k < n, Red], Line@{x, #2}} & @@@
     Thread@{c, RotateLeft@c}
    ) &~Array~n
 ,
 Axes -> 1 > 0]

```
> 13 votes

---
Tags: code-golf, graphical-output
---


title: Copy-paste master

text:
# Question
Title: 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

# Answer
### 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_i`s 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()

```
> 5 votes

# Answer
## 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
> 0 votes

---
Tags: math, popularity-contest, optimization
---


title: Maximum box gap

text:
# Question
Title: 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)

# Answer
> 5 votes
# 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)                                 ";

```

# Answer
> 5 votes
## 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]

```

# Answer
> 4 votes
## 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}`.

# Answer
> 1 votes
## 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.

# Answer
> 0 votes
## Python 2 - 54 (~~117~~104-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`.

---
Tags: code-golf
---


title: Relative vs Absolute

text:
# Question
Title: Relative vs Absolute
If someone facing north at point A in this grid wanted directions to follow the green path (as they can only follow gridlines) to point B you might tell them:

Go `North, North, West, East, East, South, East, East`.

*or equivalently*

Go `Forward, Forward, Left, Back, Forward, Right, Left, Forward`.
(Where a command of *Right*, *Left*, or *Back* implicitly means turn in that direction, then go forward.)

Write a function with one argument that translates between these absolute and relative directions **along the same path**, not just to the same point. Assume the directed person always starts facing north.

If the argument is a string of the letters `NSEW`, return the equivalent relative directions.
e.g. `f("NNWEESEE")` returns the string `FFLBFRLF`.

If the argument is a string of the letters `FBLR`, return the equivalent absolute directions.
e.g. `f("FFLBFRLF")` returns the string `NNWEESEE`.

The empty string yields itself. Assume no other input cases.

If your language does not have functions or strings use whatever seems most appropriate.

The shortest code in bytes wins.

# Answer
> 6 votes
# CJam, 57 53 49

```
{"NESW""FRBL"_3$&!!:Q$:R^^f#0\{{+0\}Q*_@-R=\}%);}

```

### Previous version

```
{"NESW""FRBL"_3$0=#W>:Q{\}*:R;f#0\{{+0\}Q*_@-R=\}%);}

```

Example:

```
{"NESW""FRBL"_3$0=#W>:Q{\}*:R;f#0\{{+0\}Q*_@-R=\}%);}:T;
"NNWEESEE"T
N
"FFLBFRLF"T

```

Output:

```
FFLBFRLF
NNWEESEE

```

### How it works

```
{
  "NESW""FRBL"             " Push the two strings. ";
  _3$0=#W>                 " Check if the first character is in FRBL. ";
  :Q                       " Assign the result to Q. ";
  {\}*                     " Swap the two strings if true. ";
  :R;                      " Assign the top string to R and discard it. ";
  f#                       " Find each character of the input in the string. ";
  0\                       " Push a 0 under the top of the stack. ";
  {                        " For each item (index of character): ";
    {                      " If Q: ";
      +0\                  " A B -> 0 (A+B) ";
    }Q*
    _@-                    " C D -> D (D-C) ";
    R=                     " E -> E-th character in R ";
    \                      " Swap the top two items. ";
  }%
  );                       " Discard the last item in the list. ";
}

```

# Answer
> 6 votes
# JavaScript (E6) 84 ~~86 88 92 104~~

Edit: using & instead of %, different operator precedence (less brackets) and works better with negative numbers
Edit2: | instead of +, op precedence again, -2. Thanks DocMax
Edit3: array comprehension is 2 chars shorter than map(), for strings

```
F=p=>[o+=c[d=n,n=c.search(i),n<4?4|n-d&3:n=n+d&3]for(i of n=o='',c='NESWFRBL',p)]&&o

```

**Test** In FireFox/FireBug console

```
console.log(F('NNWEESEE'),F('FFLBFRLF'))

```

*Output*

```
FFLBFRLF NNWEESEE

```

# Answer
> 6 votes
# C++, 99 97 94 bytes

−3 bytes thans to **ceilingcat**

The following is formatted as a lambda expression. It takes one `char*` argument and overwrites it.

```
[](char*s){for(int d=0,n=0,c=*s*9%37&4;*s;*s++="NESWFRBL"[c|n&3])d+=n=c?*s%11/3-d:n+*s%73%10;}

```

For those who are not familiar with this feature (like myself 1 hour ago), use it as follows:

```
#include <iostream>

int main()
{
    char s[] = "NNWEESEE";
    auto x = [](char*s){for(int d=0,n=0,c=*s*9%37&4;*s;d+=n)c?n=*s%11/3-d:n+=*s%73%10,*s++="NESWFRBL"[c|n&3];};

    x(s); // transform from absolute to relative
    std::cout << s << '\n';

    x(s); // transform from relative to absolute
    std::cout << s << '\n';
}

```

Some explanations:

* When using code like `flag ? (x = y) : (x += z)`, the second pair of parentheses is required in C. So I used C++ instead!
* C++ requires specifying a return type for a function. Unless I use a lambda expression, that is! An added bonus is I don't need to waste 1 character on the name of the function.
* The code `*s*9%37&4` tests the first byte; the result is 4 if it's one of `NESW`; 0 otherwise
* The code `*s%11/3` converts the bytes `NESW` to 0, 1, 2, 3
* The code `*s%73%10` converts the bytes `FRBL` to 0, 9, 6, 3 (which is 0, 1, 2, 3 modulo 4)
* When converting relative directions to absolute, I don't need the `d` variable. I tried rearranging code to eliminate it completely, but it seems impossible...

# Answer
> 4 votes
## APL, 72

```
{^/⍵∊A←'NESW':'FRBL'[1+4|-2-/4,3+A⍳⍵]⋄A[1+4|+\'RBLF'⍳⍵]}

```

If the interpreter configurations can be changed without penalty, then score is 66, by changing `⎕IO` to `0`:

```
{^/⍵∊A←'NESW':'FRBL'[4|-2-/0,A⍳⍵]⋄A[4|+\'FRBL'⍳⍵]}

```

# Answer
> 3 votes
# Python, 171 139

No way near as short as the other solutions, but I guess it should be relatively good for what can be done with Python:

```
def f(i):a,b='NWSE','FLBR';I=map(a.find,'N'+i);return''.join((b[I[k+1]-I[k]],a[sum(map(b.find,i)[:k+1])%4])[-1in I]for k in range(len(i)))

```

Expanded version for slightly better readability:

```
def f(i):
    a, b = 'NWSE', 'FLBR'
    I = map(a.find,'N'+i)     # translate to numbers assuming abs. directions
    J = map(b.index,i)        # translate to numbers assuming rel. directions
    if not -1 in I:
        o = [b[I[k+1]-I[k]] for k in range(len(i))]    # rel. dir. is differences of abs. dir.
    else:
        o = [a[sum(J[:k+1])%4] for k in range(len(i))] # abs. dir. is sum of all rel. dir. so far
    return ''.join(o)

```

# Answer
> 1 votes
**Go, 201**

```
type q string;func F(s q)q{d,z:=byte(0),make([]byte,len(s));for i,c:=range[]byte(s){if(c^4)*167%3<2{c=c*156%5;z[i],d="LBRF"[(d-c)%4],c-1;}else{c=(c^43)*3%7-1;d=(d+c)%4;z[i]="NESW"[d];};};return q(z);}

```

Readable version:

```
func F(s string) string {
    d, z, R, A := 0, make([]byte, len(s)), "LBRFLBR", "NESW"
    for i, c := range []byte(s) {
        switch c {
        case 'N': c = R[d+3]; d = 0
        case 'E': c = R[d+2]; d = 1
        case 'S': c = R[d+1]; d = 2
        case 'W': c = R[d]; d = 3
        case 'F': c = A[d]
        case 'R': d = (d + 1) % 4; c = A[d]
        case 'B': d = (d + 2) % 4; c = A[d]
        case 'L': d = (d + 3) % 4; c = A[d]
        }
        z[i] = c
    }
    return string(z)
}

```

# Answer
> 1 votes
## GNU sed, 356 bytes

The challenge calls for a simple transformation on a stream of characters. `sed`, the stream editor is the obvious choice of language ;-)

```
/[FRBL]/bx                                     # Jump to label x if relative
:y                                             # label y (start of abs->rel loop)
/[FRBL]$/q                                     # quit if string ends in rel char
s/(^|[FRBL])N/\1F/;ty                          # Substitute next abs char with
s/(^|[FRBL])E/\1R/;tr                          #     rel char, then jump to
s/(^|[FRBL])S/\1B/;tb                          #     relevant rotation label if
s/(^|[FRBL])W/\1L/;tl                          #     a match was found
by                                             # loop back to y
:r;y/NESW/WNES/;by                             # Rotation labels: transform then
:b;y/NESW/SWNE/;by                             #     loop back to y
:l;y/NESW/ESWN/;by
:x                                             # label x (start of rel->abs loop)
/^[NESW]/q                                     # quit if string starts w/ abs char
/F([NESW]|$)/s/F([NESW]|$)/N\1/                # Matches for each direction:
/R([NESW]|$)/y/NESW/ESWN/;s/R([NESW]|$)/E\1/   #     rotate, then substitute
/B([NESW]|$)/y/NESW/SWNE/;s/B([NESW]|$)/S\1/
/L([NESW]|$)/y/NESW/WNES/;s/L([NESW]|$)/W\1/
bx                                             # loop back to x

```

(Comments and spaces stripped for the purposes of golf score calculation)

### Output:

```
$ sed -rf absrel.sed <<< NNWEESEE
FFLBFRLF
$ sed -rf absrel.sed <<< FFLBFRLF
NNWEESEE
$

```

### Explanation:

The idea here is that when we change the frame of reference, there is always a direct mapping between `{N, E, S, W}` and `{F, R, B, L}`.

In the case of absolute to relative, we work fowards through the string. For each character we map `{N, E, S, W}` to `{F, R, B, L}`, then rotate the remaining `[NESW]` characters according to the character we just mapped, then move onto the next character.

For the case of relative to absolute we do the reverse. We work backwards through the string, rotating all following `[NESW]` characters according to the character immediately in front. Then we map that character `{N, E, S, W}` to `{F, R, B, L}`, until we get to the start of the string.

# Answer
> 0 votes
# Haskell, 224

```
import Data.Function
i=flip(\x->length.takeWhile(/=x))
r=['F','R','B','L']
a=['N','E','S','W']
f s@(x:_)|elem x a=map((r!!).(`mod`4).(4-))$zipWith((-)`on`(i a))('N':s)(s)|True=tail$map((a!!).(`mod`4)).scanl(+)(0)$map(i r) s

```

This assigns rotation numbers to the relative directions, and orientation numbers to the absolute directions, then either finds the rotations between successive orientations or the orientations after successive rotations. The `i` function finds the index within the two legends.

---
Tags: code-golf
---


title: Enclose 1009 pixels

text:
# Question
Title: Enclose 1009 pixels
**Output** is a shape that encloses 1009 pixels.

* The shape must take the form of a single, closed, non-intersecting loop.

**Input** is a positive non-zero integer.

* Each input must yield output that is unique — that is, each output must be unique from those generated using a lower input.

**Victory** is decided by the largest input limit:

* Your submission's input limit is regarded as 1 less than the lowest input that gives non-unique or otherwise invalid output.
* For instance, if valid and unique output is produced for an input of 1, 2 or 3 but not 4, your input limit is 3.

There is a 1009 byte limit on source code. If there is a draw the entry with the fewest bytes wins.

---

**Restrictions and clarifications:**

* A shape's maximum size is 109 by 109 pixels. Size includes the line used to draw the shape.
* A line is constant width.
* The enclosed space must be entirely enclosed by the line - you can't use the boundary of the image file.
* The enclosed 1009 pixels refers only to enclosed space. It does not include the line.
* Output is an image.
* There are no further graphical restrictions - e.g. on colour, line thickness etc.
* An output's uniqueness refers only to the enclosed space. Changes to the line or other graphical changes are irrelevant if the enclosed space is not unique.
* A translation of shape isn't unique. Rotations, reflections and any other transformations count as unique.
* Output must be reproducible — the same input will always give the same output
* There needn't be a relation between outputs, consecutive or otherwise.
* Outside of a submission's 'input limit' there is no defined output.
* No other input or fetching of external data is permitted.
* A line must be continuous — i.e. pixels must touch (touching a corner counts).
* A pixel is the smallest unit of 'drawing' used by your method of drawing, and won't necessarily correspond to a screen pixel.

---

**Examples:**

* Here is an example of a valid shape:
* The following shapes are invalid:

EDIT: **Line touching:**

* Enclosed space must be continuous which is defined as pixels touching. Touching corners counts.
* A line cannot enclose any space on its outer side. This image posted by @Sparr illustrates this point - only the first shape on each row are valid:
* The outer sides of a line may touch, but not in a way that encloses space.
* Touching lines may not overlap - e.g. two touching 1 pixel thick lines would have a combined thickness of 2px, never 1px.

# Answer
> 25 votes
## Python + Pycairo, 2100 shapes

Let's start with the obvious.

```
from cairo import *
from sys import argv

n = int(argv[1]) - 1

s = ImageSurface(FORMAT_ARGB32, 109, 109); c = Context(s)
c.set_antialias(ANTIALIAS_NONE); c.set_line_width(1); c.translate(54, 54)
def pixel(x, y): c.rectangle(x, y, 1, 1); c.fill()

W, H, R = 100, 10, 9
X1, Y1 = -W / 2 - 1, -H / 2 - 1
X2, Y2 = X1 + W + 1, Y1 + H + 1

pixel(X2 - 1, Y1)
c.move_to(X1, Y1 + 1); c.line_to(X1, Y2 + 1)
c.move_to(X2 + 1, Y1); c.line_to(X2 + 1, Y1 + R + 1);
c.move_to(X2, Y1 + R + 1); c.line_to(X2, Y2 + 1)
c.stroke()

for i in xrange(W):
    offset = (n >> i) & 1
    for y in Y1, Y2: pixel(X1 + i, y + offset)

s.write_to_png("o.png")

```

Takes the number on the command line and writes `o.png`.

# Answer
> 19 votes
# BBC Basic, score 10^288 (minus 1 if zero not counted)

Download interepreter at http://sourceforge.net/projects/napoleonbrandy/ (not my usual BBC basic interpreter, that one doesn't support long enough strings.)

To encode a lot of information, you need a lot of perimeter. That means a thin shape. I start with a vertical bar of 49 pixels at the left, and add ten tentacles of 96 pixels to it. Each tentacle can encode 96 bits in a similar manner to @ell's solution, a total of 960 bits.

As BBC Basic cannot handle numbers that large, a number of up to 288 decimal digits is input as a string, and each set of 3 decimal digits is converted to a 10-bit binary number. Each bit is then used to wiggle one of the tentacles up by one pixel if it is a `1` (but not if it is a `0`.) The program can handle up to 288/3=96 such sets of 3 digits

```
    1MODE1:VDU19,0,7;0;19,15,0;0;               :REM select an appropriate screen mode and change to black drawing on white background
   10INPUT a$
   20a$=STRING$(288-LEN(a$)," ")+a$             :REM pad input up to 288 characters with leading spaces
   50RECTANGLE0,0,8,200                         :REM draw a rectangle at the left, enclosing 49 pixels
   60FOR n=0 TO 95
   70  b=VAL(MID$(a$,n*3+1,3))                  :REM extract 3 characters from a$ and convert to number
   80  FOR m=0 TO 9                             :REM plot the ten tentacles
   90    PLOT71,n*4+8,m*20+8+(b/2^m AND 1)*4    :REM plot (absolute coordinates) a background colour pixel for tentacle m at horizontal distance n
  100    POINT BY 0,-4                          :REM offsetting vertically by 1 pixel according to the relevant bit of b
  110    POINT BY 4,4
  120    POINT BY -4,4                          :REM then plot foreground colour pixels (relative coordinates) above, below and to the right.
  130  NEXT
  140NEXT

```

**Output**

A typical output for a 288-digit number. Note that 999 is 1111100111 in binary. You can see how the sets of 9 digits cause the tentacles to undulate.

**Technicalities**

A.The answer to Martin's point 3 "is the shape connected if its pixel's touch only along a corner?" was "yes" so I understand my answer complies. Nevertheless, if you alternate (for example) 999's and 000's in every row, it looks very busy.

B. If we view this as a rectangle with bites taken out of the side, you can see that I allowed three pixels between each pair of adjacent tentacles, to ensure that the black line round the outside never touches itself. There is no specific rule on this (I hope my reason for asking is clearer in the light of my answer.) If the line is allowed to touch itself on the OUTSIDE of the shape, I could move the tentacles together and use less pixels for the vertical bar (and so make the tentacles a bit longer.) It would, however become very confusing to determine by eye whether a pixel was inside or outside the shape, so I think my interpretation that the outside of the black line should never touch itself is best.

C. BBC basic in this screen mode treats a 2x2 square of screen pixels as a single pixel. I've left this as it is, because it helps viewing if the shape is not too tiny. Each one of these BBC basic pixels is considered as a box of 4x4 logical units. From the start, the developers of BBC basic had the foresight to realise that one day screen resolutions would increase, so they made the logical resolution higher than the physical resolution.

# Answer
> 6 votes
## Mathematica, 496 bytes, Score: large-ish (\>1157)

The lower bound I've got there is ridiculously low, but I haven't found a better way than brute force to check yet.

```
SeedRandom@Input[];
g = 0 &~Array~{109, 109};
g[[2, 2]] = 1;
h = {{2, 2}};
For[n = 1, n < 1009,
  c = RandomChoice@h;
  d = RandomChoice[m = {{1, 0}, {0, 1}}];
  If[FreeQ[e = c + d, 1 | 109] &&
    Count[g[[2 ;; e[[1]], 2 ;; e[[2]]]], 0, 2] == 1,
   ++n;
   h~AppendTo~e;
   g[[## & @@ e]] = 1
   ];
  ];
(
    c = #;
    If[e = c + #; g[[## & @@ e]] < 1,
       g[[## & @@ e]] = 2
       ] & /@ Join @@ {m, -m}) & /@ h;
ArrayPlot[g, ImageSize -> 109, PixelConstrained -> True,
 Frame -> 0 > 1]

```

I haven't golfed this yet, because there was no need to. I'll do that once someone proves they are actually tying with me.

The algorithm is basically doing a flood-fill from the top-left corner of the 109x109 image (offset by one pixel to allow for the line) and when I've flooded 1009 cells, I stop and mark the border. You said colours are up to us, so the background is white, the line is black and the interior is grey (I can remove the gray for a handful of characters if necessary).

The flood fill is quite constrained, but that ensures that I don't have to worry about about holes. Relaxing these constraints will probably dramatically increase my (yet unknown) score.

I'll try to put some lower bounds on the score now.

# Answer
> 1 votes
# Python 2, Score \> 10^395

It is extremely slow, and I haven't actually managed to get any result other than n=0, but if you want to test it lower `SIZE` (the number of pixels) and `BOUND` the maximum side length of the bounding square and you should be able to get plenty of results. It was very difficult to try and calculate how many it would produce; I am fairly confident that the lower bound I give is accurate, but I suspect the actual count to be significantly larger, and I may try to improve on it later.

```
import sys
import pygame
sys.setrecursionlimit(1100)

def low(s):
    return min(sum(e[1] for e in s[:i+1]) for i in range(len(s)))
def high(s):
    return max(sum(e[1] for e in s[:i+1])+s[i][0] for i in range(len(s)))

BOUND = 109
SIZE = 1009

def gen(n,t=0):
    if n <= (BOUND-t)*BOUND:
        for i in range(1,min(n,BOUND)):
            for r in gen(n-i,t+1):
                a,b=r[0]
                for x in range(max(1-a,high(r)-low(r)-BOUND),i):
                    yield [(i,0),(a,x)]+r[1:]
        yield [(n,0)]

def create(n):
    g=gen(SIZE)
    for i in range(n+1):shape=g.next()
    s=pygame.Surface((BOUND+2,BOUND+2))
    l=low(shape);x=0
    for y,(t,o) in enumerate(shape):
        x+=o;pygame.draw.line(s,(255,255,255),(x-l+1,y+1),(x-l+t,y+1))
    out=[]
    for x in range(BOUND+2):
        for y in range(BOUND+2):
            if all((0,0,0)==s.get_at((x+dx,y+dy))for dx,dy in[(-1,0),(1,0),(0,-1),(0,1)]if 0<=x+dx<BOUND+2 and 0<=y+dy<BOUND+2):
                out.append((x,y))
    for x,y in out:
        s.set_at((x,y),(255,255,255))
    pygame.image.save(s,"image.png")

```

---
Tags: code-challenge, graphical-output, geometry
---


# Question
Title: Move the "post your answer" form next to the question on SE sites
I have a problem when posting an answer to a question that already have several answers and/or several comments:

The "post your answer" form sits on bottom, the answer is on top. There is an awful lot of "clutter" between them, that are not needed for the act of posting a new answer (yes, I've read the other answers and comments, what I am about to write is original).

I have a very short short term memory and hate to scroll all the way up and down to read question and write answer text.

Write a script or program that

* Can run on vanilla (downloaded from the main page for those softwares) Firefox and/or Chrome (irrelevant if it also runs on other browsers or on all browsers)
you get 10 fake internet points from me if it runs on all browsers, but this is not a victory condition
* You can call any code that ships with the browser, loads with the SE page (like jQuery) or sideloads from the web.
* Can be run (as a bookmarklet, from console, any input method) on a fresh install of one of those two browsers.
* Does not depend on any other software installed on the machine, or the installation of any add-ons and/or plugins on the browsers.
* Irrelevant if it runs only on windows, only on mac or only on linux, as long as those browsers can be downloaded from the browsers' official download page, for that platform.
* Does not break the submit answer form (I can still write my answer and submit, and the whole edit toolbar is still intact - including the help icon).
* Question is intact. Title, body, votes panel, post menu and owner signature.

(italics denote editted-in content)

* *vertical* Distance between *bottom* of owner signature and *the top* of edit toolbar is the same or smaller *(negatives allowed)* than when posting the first answer to a question in the same site.
* *Edit form toolbar cannot be higher than the question title.*

+ *both question, answer edit form, answer toolbar and answer preview have to remain visible and non-overlapping.*
* Only the screen display matters. If the other elements were hidden, deleted, moved, ejected into outer space or phase-shifted into a Dirac Sea is irrelevant.

Your code must work for a minimum of:

This is , so the shortest code in bytes will win!

---

I am now required to link this question for the exerpts' credits. Thanks @Doorknob.

P.S.: It is my first time in PpCG, be kind.

# Answer
> 4 votes
## JavaScript, ~~35~~ 34 bytes

```
$(answers).before($('#post-form'))

```

# Answer
> 2 votes
## JavaScript (38 bytes)

```
$('#question').append($('#post-form'))

```

---
Tags: code-golf, javascript, browser
---