title: Balance chemical equations!

text:
# Question
Title: Balance chemical equations!
Bernd is a high school student who has some problems in chemistry. In class he has to design chemical equations for some experiments they are doing, such as the combustion of heptane `C7H16`:

> C7H16 \+ 11O2 → 7CO2 \+ 8H2O

Since mathematics isn't exactly Bernd's strongest subject, he often has a hard time finding the exact ratios between the pro- and educts of the reaction. Since you are Bernd's tutor, it is your job to help him! Write a program, that calculates the amount of each substance needed to get a valid chemical equation.

## Input

The input is a chemical equation without amounts. In order to make this possible in pure ASCII, we write any subscriptions as ordinary numbers. Element names always start with a capital letter and may be followed by a minuscule. The molecules are separated with `+` signs, an ASCII-art arrow `->` is inserted between both sides of the equation:

```
Al+Fe2O4->Fe+Al2O3

```

The input is terminated with a newline and won't contain any spaces. If the input is invalid, your program may do whatever you like.

You may assume, that the input is never longer than `1024` characters. Your program may either read the input from standard input, from the first argument or in an implementation defined way at runtime if neither is possible.

## Output

The output of your program is the input equation augmented with extra numbers. The number of atoms for each element must be the same on both sides of the arrow. For the example above, a valid output is:

```
2Al+Fe2O3->2Fe+Al2O3

```

If the number for a molecule is `1`, drop it. A number must always be a positive integer. Your program must yield numbers such that their sum is minimal. For instance, the following is illegal:

```
40Al+20Fe2O3->40Fe+20Al2O3

```

If there is no solution, print

```
Nope!

```

instead. A sample input that has no solution is

```
Pb->Au

```

# Testcases

Input-\>Output

```
C7H16+O2->CO2+H2O
C7H16+11O2->7CO2+8H2O

Al+Fe2O3->Fe+Al2O3
2Al+Fe2O3->2Fe+Al2O3

Pb->Au
Nope!

```

This is , so shortest code wins!

Your program must terminate in reasonable time for all reasonable inputs

# Answer
# C (gcc), 442 bytes

```
u,t[99];char*s,*m[99];c,v[99][99];i,j,n;
b(k){if(k<0)for(n=j=0;!n&&j<u;j++)for(i=0;i<=c;i++)n+=t[i]*v[i][j];else for(t[k]=0;n&&t[k]++<30;)b(k-1);}
main(int r,char**a){for(s=m[0]=a[1];*s;){if(*s==45)r=0,s++;if(*s<65)m[++c]=++s;j=*s++;if(*s>96)j=*s+++j<<8;for(i=0,t[u]=j;t[i]-j;i++);u+=i==u;for(n=0;*s>>4==3;)n=n*10+*s++-48;n+=!n;v[c][i]=r?n:-n;}b(c);for(i=0,s=n?"Nope!":a[1];*s;putchar(*s++))s==m[i]&&t[i++]>1?printf("%d",t[i-1]):0;putchar(10);}

```

Try it online!

Ungolfed version

// element use table, then once parsed reused as molecule weights
u,t[99];

// molecules
char*s,*m[99]; // name and following separator
c,v[99][99]; // count-1, element vector

i,j,n;

// brute force solver, n==0 upon solution - assume at most 30 of each molecule
b(k){
    if(k<0)for(n=j=0;!n&&j<u;j++)for(i=0;i<=c;i++)n+=t[i]*v[i][j]; // check if sums to zero
    else for(t[k]=0;n&&t[k]++<30;)b(k-1); // loop through all combos of weights
}

main(int r,char**a){
    // parse
    for(s=m[0]=a[1];*s;){
        // parse separator, advance next molecule
        if(*s==45)r=0,s++;
        if(*s<65)m[++c]=++s;
        // parse element
        j=*s++;
        if(*s>96)j=*s+++j<<8;
        // lookup element index
        for(i=0,t[u]=j;t[i]-j;i++);
        u+=i==u;
        // parse amount
        for(n=0;*s>>4==3;)n=n*10+*s++-48;
        n+=!n;
        // store element count in molecule vector, flip sign for other side of '->'
        v[c][i]=r?n:-n;
    }
    // solve
    b(c);
    // output
    for(i=0,s=n?"Nope!":a[1];*s;putchar(*s++))s==m[i]&&t[i++]>1?printf("%d",t[i-1]):0;
    putchar(10);
}
```
</code></pre>
> 8 votes

# Answer
# Wolfram Language (Mathematica), 510 bytes

I employed the augmented chemical composition matrix approach described in

L.R.Thorne, An innovative approach to balancing chemical - reaction equations : a simplified matrix - inverse technique for determining the matrix null space. *Chem.Educator*, 2010, 15, 304 - 308.

One slight tweak was added: I divided the transpose of the null-space vector by the greatest common divisor of the elements to ensure integer values in any solutions. My implementation does not yet handle cases where there is more than one solution to balancing the equation.

```
b@t_ :=Quiet@Check[Module[{s = StringSplit[t, "+" | "->"], g = StringCases, k = Length,
  e, v, f, z, r},
e = Union@Flatten[g[#, _?UpperCaseQ ~~ ___?LowerCaseQ] & /@ s];v = k@e;
s_~f~e_ := If[g[s, e] == {}, 0, If[(r = g[s, e ~~ p__?DigitQ :> p]) == {}, 1,
   r /. {{x_} :> ToExpression@x}]];z = k@s - v;
r = #/(GCD @@ #) &[Inverse[Join[SparseArray[{{i_, j_} :> f[s[[j]], e[[i]]]}, k /@ {e, s}],
Table[Join[ConstantArray[0, {z, v}][[i]], #[[i]]], {i, k[#]}]]][[All, -1]] &
   [IdentityMatrix@z]];
Row@Flatten[ReplacePart[Riffle[Partition[Riffle[Abs@r, s], 2], " + "],2 Count[r,_?Negative]->" -> "]]],"Nope!"]

```

Try it online!

**Analysis**

It works by setting up the following chemical composition table, consisting of chemical species by elements, to which an addition nullity vector is added (becoming the augmented chemical composition table:

The inner cells are removed as a matrix and inverted, yielding.

The right-most column is extracted, yielding:

> {-(1/8), -(11/8), 7/8, 1}

Each element in the vector is divided by the gcd of the elements (1/8), giving:

> {-1, -11, 7, 8}

where the negative values will be placed on the left side of the arrow. The absolute values of these are the numbers needed to balance the original equation:
> 8 votes

# Answer
# Python 2, 879 bytes

```
import sys,re
from sympy.solvers import solve
from sympy import Symbol
from fractions import gcd
from collections import defaultdict

Ls=list('abcdefghijklmnopqrstuvwxyz')
eq=sys.argv[1]
Ss,Os,Es,a,i=defaultdict(list),Ls[:],[],1,1
for p in eq.split('->'):
 for k in p.split('+'):
  c = [Ls.pop(0), 1]
  for e,m in re.findall('([A-Z][a-z]?)([0-9]*)',k):
   m=1 if m=='' else int(m)
   a*=m
   d=[c[0],c[1]*m*i]
   Ss[e][:0],Es[:0]=[d],[[e,d]]
 i=-1
Ys=dict((s,eval('Symbol("'+s+'")')) for s in Os if s not in Ls)
Qs=[eval('+'.join('%d*%s'%(c[1],c[0]) for c in Ss[s]),{},Ys) for s in Ss]+[Ys['a']-a]
k=solve(Qs,*Ys)
if k:
 N=[k[Ys[s]] for s in sorted(Ys)]
 g=N[0]
 for a1, a2 in zip(N[0::2],N[1::2]):g=gcd(g,a2)
 N=[i/g for i in N]
 pM=lambda c: str(c) if c!=1 else ''
 print '->'.join('+'.join(pM(N.pop(0))+str(t) for t in p.split('+')) for p in eq.split('->'))
else:print 'Nope!'

```

Try it online!

Could be much less than 880, but my eyes are killing me already...
> 4 votes

# Answer
# Python 2, 640 bytes

previous byte counts: 794, 776, 774, 765, 759, 747, 735, 734, 720, 683, 658, 655, 654, 653, 651, 640

The second indentation level is only a tab, the third is a tab then a space.

To be honest, this is jadkik94's answer, but so many bytes were shaved, I had to do it. Tell me if I can shave any bytes off!

```
from sympy import*
import sys,re
from sympy.solvers import*
from collections import*
P=str.split
L=map(chr,range(97,123))
q=sys.argv[1]
S,O,a,i,u,v=defaultdict(list),L[:],1,1,'+','->'
w=u.join
for p in P(q,v):
 for k in P(p,u):
  c=L.pop(0)
  for e,m in re.findall('([A-Z][a-z]*)(\d*)',k):
   m=int(m or 1)
   a*=m
   S[e][:0]=[c,m*i],
 i=-1
Y=dict((s,Symbol(s))for s in set(O)-set(L))
Q=[eval(w('%d*%s'%(c[1],c[0])for c in S[s]),{},Y)for s in S]+[Y['a']-a]
k=solve(Q,*Y)
if k:
 N=[k[Y[s]]for s in sorted(Y)]
 g=gcd(N[:1]+N[1::2])
 print v.join(w((lambda c:str(c)*(c!=1))(N.pop(0)/g)+str(t)for t in P(p,u))for p in P(q,v))
else:print'Nope!'

```

Try it online!
> 2 votes

# Answer
# JavaScript, 682 bytes

```
x=>{m=1;x.split(/\D+/g).map(i=>i?m*=i:0);e=new Set(x.replace(/\d+|\+|->/g,"").match(/([A-Z][a-z]*)/g));e.delete``;A=[];for(let z of e){t=x.split`->`;u=[];for(c=1;Q=t.shift();c=-1)Q.split`+`.map(p=>u.push(c*((i=p.indexOf(z))==-1?0:(N=p.substring(i+z.length).match(/^\d+/g))?N[0]:1)));A.push(u)}J=A.length;for(P=0;P<J;P++){for(i=P;!A[i][P];i++);W=A.splice(i,1)[0];W=W.map(t=>t*m/W[P]);A=A.map(r=>r[P]?r.map((t,j)=>t-W[j]*r[P]/m):r);A.splice(P,0,W)}f=e.size;if(!A[0][f])return"Nope!";g=m=-m;_=(a,b)=>b?_(b,a%b):a;c=[];A.map(p=>c.push(t=p.pop())&(g=_(g,t)));c.push(m);j=x.match(/[^+>]+/g);return c.map(k=>k/g).map(t=>(t^1?t:"")+(z=j.shift())+(z.endsWith`-`?">":"+")).join``.slice(0,-1);}
```

This is a much more golfed (decades of characters!) of Kuilin's answer. Might be noncompeting because certain JS features postdate the challenge.
> 1 votes

# Answer
# Javascript, 705 bytes

**(non-competing, some features postdate the challenge)**

Other solutions all had elements of brute-forcing. I tried for a more deterministic approach by representing the chemical equation as a set of linear equations, and then solving using the Gauss-Jordan algorithm to take the reduced row-echelon form of that matrix. In order to isolate out the trivial case where everything is zero, I assume that one of the elements is a constant number - and that number is determined by just all the numbers multiplied together, in order to not have fractions. Then as a final step we'll divide each by the gcd to satisfy the last condition.

Ungolfed:

```
function solve(x) {
 //firstly we find bigNumber, which will be all numbers multiplied together, in order to assume the last element is a constant amount of that
 bigNumber = 1;
 arrayOfNumbers = new Set(x.split(/\D+/g));
 arrayOfNumbers.delete("");
 for (let i of arrayOfNumbers) bigNumber *= parseInt(i);

 //first actual step, we split into left hand side and right hand side, and then into separate molecules
 //number of molecules is number of variables, number of elements is number of equations, variables refer to the coefficients of the chemical equation
 //note, the structure of this is changed a lot in the golfed version since right is the same as negative left
 left = x.split("->")[0].split("+");
 righ = x.split("->")[1].split("+");
 molecules = left.length + righ.length;

 //then let's find what elements there are - this will also become how many equations we have, or the columns of our matrix minus one
 //we replace all the non-element characters, and then split based on the uppercase characters
 //this also sometimes adds a "" to the array, we don't need that so we just delete it
 //turn into a set in order to remove repeats
 elems = new Set(x.replace(/\d+|\+|->/g,"").match(/([A-Z][a-z]*)/g));
 elems.delete("");

 rrefArray = [];//first index is rows, second index columns - each row is an equation x*(A11)+y*(A21)+z*(A31)=A41 etc etc, to solve for xyz as coefficients
 //loop thru the elements, since for each element we'll have an equation, or a row in the array
 for (let elem of elems) {
  buildArr = [];
  //loop thru the sides
  for (let molecule of left) {
   //let's see how many of element elem are in molecule molecule
   //ASSUMPTION: each element happens only once per molecule (no shenanigans like CH3COOH)
   index = molecule.indexOf(elem);
   if (index == -1) buildArr.push(0);
   else {
    index += elem.length;
    numberAfterElement = molecule.substring(index).match(/^\d+/g);
    if (numberAfterElement == null) buildArr.push(1);
    else buildArr.push(parseInt(numberAfterElement));
   }
  }
  //same for right, except each item is negative
  for (let molecule of righ) {
   index = molecule.indexOf(elem);
   if (index == -1) buildArr.push(0);
   else {
    index += elem.length;
    numberAfterElement = molecule.substring(index).match(/^\d+/g);
    if (numberAfterElement == null) buildArr.push(-1);
    else buildArr.push(parseInt(numberAfterElement)*(-1));
   }
  }
  rrefArray.push(buildArr);
 }

 //Gauss-Jordan algorithm starts here, on rrefArray
 for (pivot=0;pivot<Math.min(molecules, elems.size);pivot++) {
  //for each pivot element, first we search for a row in which the pivot is nonzero
  //this is guaranteed to exist because there are no empty molecules
  for (i=pivot;i<rrefArray.length;i++) {
   row = rrefArray[i];
   if (row[pivot] != 0) {
    workingOnThisRow = rrefArray.splice(rrefArray.indexOf(row), 1)[0];
   }
  }
  //then multiply elements so the pivot element of workingOnThisRow is equal to bigNumber we determined above, this is all to keep everything in integer-space
  multiplyWhat = bigNumber / workingOnThisRow[pivot]
  for (i=0;i<workingOnThisRow.length;i++) workingOnThisRow[i] *= multiplyWhat
  //then we make sure the other rows don't have this column as a number, the other rows have to be zero, if not we can normalize to bigNumber and subtract
  for (let i in rrefArray) {
   row = rrefArray[i];
   if (row[pivot] != 0) {
    multiplyWhat = bigNumber / row[pivot]
    for (j=0;j<row.length;j++) {
     row[j] *= multiplyWhat;
     row[j] -= workingOnThisRow[j];
     row[j] /= multiplyWhat;
    }
    rrefArray[i]=row;
   }
  }
  //finally we put the row back
  rrefArray.splice(pivot, 0, workingOnThisRow);
 }

 //and finally we're done!
 //sanity check to make sure it succeeded, if not then the matrix is insolvable
 if (rrefArray[0][elems.size] == 0 || rrefArray[0][elems.size] == undefined) return "Nope!";

 //last step - get the results of the rref, which will be the coefficients of em except for the last one, which would be bigNumber (1 with typical implementation of the algorithm)
 bigNumber *= -1;
 gcd_calc = function(a, b) {
  if (!b) return a;
  return gcd_calc(b, a%b);
 };
 coEffs = [];
 gcd = bigNumber;
 for (i=0;i<rrefArray.length;i++) {
  num = rrefArray[i][molecules-1];
  coEffs.push(num);
  gcd = gcd_calc(gcd, num)
 }
 coEffs.push(bigNumber);
 for (i=0;i<coEffs.length;i++) coEffs[i] /= gcd;

 //now we make it human readable
 //we have left and right from before, let's not forget those!
 out = "";
 for (i=0;i<coEffs.length;i++) {
  coEff = coEffs[i];
  if (coEff != 1) out += coEff;
  out += left.shift();
  if (left.length == 0 && righ.length != 0) {
   out += "->";
   left = righ;
  } else if (i != coEffs.length-1) out += "+";
 }
 return out;
}
console.log(solve("Al+Fe2O4->Fe+Al2O3"));
console.log(solve("Al+Fe2O3->Fe+Al2O3"));
console.log(solve("C7H16+O2->CO2+H2O"));
console.log(solve("Pb->Au"));
```

Golfed

```
s=x=>{m=1;x.split(/\D+/g).map(i=>i!=""?m*=i:0);e=(new Set(x.replace(/\d+|\+|->/g,"").match(/([A-Z][a-z]*)/g)));e.delete("");A=[];for(let z of e){t=x.split("->");u=[];for(c=1;Q=t.shift();c=-1)Q.split("+").map(p=>u.push(c*((i=p.indexOf(z))==-1?0:(N=p.substring(i+z.length).match(/^\d+/g))?N[0]:1)));A.push(u)}J=A.length;for(P=0;P<J;P++){for(i=P;!A[i][P];i++);W=A.splice(i,1)[0];W=W.map(t=>t*m/W[P]);A=A.map(r=>!r[P]?r:r.map((t,j)=>t-W[j]*r[P]/m));A.splice(P,0,W)}f=e.size;if (!A[0][f])return "Nope!";g=m=-m;_=(a,b)=>b?_(b,a%b):a;c=[];A.map(p=>c.push(t=p.pop())&(g=_(g,t)));c.push(m);j=x.match(/[^+>]+/g);return c.map(k=>k/g).map(t=>(t==1?"":t)+(z=j.shift())+(z.endsWith("-")?">":"+")).join("").slice(0,-1);}

console.log(s("Al+Fe2O4->Fe+Al2O3"));
console.log(s("Al+Fe2O3->Fe+Al2O3"));
console.log(s("C7H16+O2->CO2+H2O"));
console.log(s("Pb->Au"));
```
> 0 votes

---
Tags: code-golf, string, chemistry
---


title: Robot on a ladder

text:
# Question
Title: Robot on a ladder
## Background

I have a ladder leaning on a wall, and a remote-controlled robot that can climb it. I can send three different commands to the robot:

* `UP`: the robot takes one step upwards. If it was on the highest step, it trips over, falls down and explodes.
* `DOWN`: the robot takes one step downwards. If it was on the lowest step, nothing happens.
* `RESET`: the robot returns to the lowest step.

I can also send a series of commands, and the robot will execute them one by one. Your task is to predict its movements.

## Input

Your inputs are a positive integer `N`, representing the number of steps in the ladder, and a non-empty string `C` over `UDR`, representing the commands I have sent to the robot. You can assume that `N < 1000`. The robot is initialized on the lowest step of the ladder.

## Output

It is guaranteed that at some point, the robot will climb over the highest step and explode. Your output is the number of commands it executes before this happens.

## Example

Consider the inputs `N = 4` and `C = "UDDUURUUUUUUUDDDD"` The robot, denoted by `@`, moves along the 4-step ladder as follows:

```
|-|   |-|   |-|   |-|   |-|   |-|   |-|   |-|   |-|   |@|   |-||
|-|   |-|   |-|   |-|   |-|   |@|   |-|   |-|   |@|   |-|   |-||
|-|   |@|   |-|   |-|   |@|   |-|   |-|   |@|   |-|   |-|   |-|v
|@| U |-| D |@| D |@| U |-| U |-| R |@| U |-| U |-| U |-| U |-|# Boom!

```

The remaining commands are not executed, since the robot has exploded. The explosion took place after 10 commands, so the correct output is `10`.

## Rules and scoring

You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.

## Test cases

```
  1 U -> 1
  1 DDRUDUU -> 4
  4 UDDUUUUURUUUUDDDD -> 7
  4 UDDUURUUUUUUUDDDD -> 10
  6 UUUUUDRUDDDDRDUUUUUUDRUUUUUUUDR -> 20
 10 UUUUUURUUUUUUURUUUUUUUURUUUUUUUUUUUUUU -> 34
  6 UUUDUUUUDDDDDDDDDDDDDDRRRRRRRRRRRUUUUUU -> 8
  6 UUUDUUUDURUDDDUUUUUDDRUUUUDDUUUUURRUUDDUUUUUUUU -> 32
 20 UUDDUDUUUDDUUDUDUUUDUDDUUUUUDUDUUDUUUUUUDUUDUDUDUUUUUDUUUDUDUUUUUUDUDUDUDUDUUUUUUUUUDUDUUDUDUUUUU -> 56
354 UUDDUUDUDUUDDUDUUUUDDDUDUUDUDUDUDDUUUUDUDUUDUDUUUDUDUDUUDUUUDUUUUUDUUDUDUUDUDUUUUUDUDUUDUDUDUDDUUUUUUUDUDUDUDUUUUUDUDUDUDUDUDUDUDUUDUUUUUURUUUDUUUUDDUUDUDUDURURURUDUDUUUUDUUUUUUDUDUDUDUDUUUUUUDUDUUUUUUUDUUUDUUDUDUDUUDUDUDUUUUUUUUUUDUUUDUDUUDUUDUUUDUUUUUUUUUUUUUDUUDUUDUDUDUUUDUDUUUUUUUDUUUDUUUDUUDUUDDUUUUUUUUDUDUDUDUDUUUUDUDUUUUUUUUDDUUDDUUDUUDUUDUDUDUDUUUUUUUUUDUUDUUDUUUDUUDUUUUUUUUUUUDUDUDUDUUUUUUUUUUUUDUUUDUUDUDDUUDUDUDUUUUUUUUUUUUDUDUDUUDUUUDUUUUUUUDUUUUUUUUUDUDUDUDUDUUUUUUDUDUDUUDUDUDUDUUUUUUUUUUUUUUUDUDUDUDDDUUUDDDDDUUUUUUUUUUUUUUDDUDUUDUUDUDUUUUUUDUDUDUDUDUUUUDUUUUDUDUDUUUDUUDDUUUUUUUUUUUUUUUUUUDUUDUUDUUUDUDUUUUUUUUUUUDUUUDUUUUDUDUDUUUUUUUUUDUUUDUUUDUUDUUUUUUUUUUUUDDUDUDUDUUUUUUUUUUUUUUUDUUUDUUUUDUUDUUDUUUUUUUUUUUDUDUUDUUUDUUUUUUDUDUDUUDUUUUUUUUUUUUDUUUDUUDUDUDUUUUDUDUDUDUDUUUUUUUUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUUU -> 872

```

# Answer
## CJam, ~~26~~ ~~25~~ 22 bytes

```
0l{i"()~ "=~0e>_}%ri#)

```

Input format is the instructions on the first line and the ladder height on the second.

Test it here.

### Explanation

```
0         e# Push a 0 - the initial position of the robot.
l         e# Read the instructions.
{         e# Map this block over the instruction...
  i       e#   Convert to character code. D -> 68, U -> 85, R -> 82.
  "()~ "= e#   We use these as cyclic indices into this array. Note that the values
          e#   modulo 4 are 0, 1 and 2, respectively. So U -> ) (increment),
          e#   D -> ( (decrement), R -> ~ (bitwise NOT, i.e negated and decrement).
  ~       e#   Evaluate the character as code.
  0e>     e#   Clamp to non-negative numbers. So D can't go below 0, and since R is
          e#   guaranteed to yield something negative, this resets it to zero.
  _       e#   Duplicate, so we keep one copy of the current position on the stack.
}%        e# Since this was a map, the result will be wrapped in an array.
ri        e# Read the ladder height and convert it to an integer.
#         e# Find its first occurrence in the list of positions.
)         e# The result is off by one, so we increment it.

```
> 10 votes

# Answer
# C, ~~83~~ 71 + 4 = 75 bytes

Thanks @Josh for showing me the K&S style, which allowed 8 bytes off !!

```
f(i,s,z,a)char*s;{z-=*s<82?z>0:*s>82?-1:z;return z-i?f(i,s+1,z,a+1):a;}

```

Explaining:

```
f(i,s,z,a)char*s;{ // function needs one integer and one "string"
  z-=              // z is the bot's height
    *s<82?         // if 'Down'
      z>0          // then subtract 1 when z>0 or nothing otherwise
    :*s>82?        // else if 'Up'
      -1           // increase height z-=-1
    :z;            // else reset z=z-z
  return z-i?      // if z is not the max height
    f(i,s+1,z,a+1) // try next step
  :a;              // else print how many calls/steps were made
}                  // end of function

```

Example call:

```
f(1,"U",0,1);    // I've added 4 bytes in the score because of ",0,1"

```

Live test on **ideone**
> 7 votes

# Answer
# JavaScript (ES6), ~~54~~ 53 bytes

```
n=>c=>(f=p=>n-p?f({D:p&&p-1,U:p+1}[c[i++]]|0):i)(i=0)

```

## Explanation

Uses a recursive function internally.

```
var solution =

n=>c=>(
  f=p=>             // f = recursive function, p = position of robot on ladder
    n-p?            // if p != n
      f({           // execute the next command
          D:p&&p-1, // D -> p = max of p - 1 and 0
          U:p+1     // U -> p = p + 1
        }[c[i++]]   // get current command then increment i (current command index)
        |0          // R -> p = 0
      )
    :i              // else return the current command index
)(i=0)              // initialise p and i to 0 for the first recurse
```

```
N = <input type="number" id="N" value="354" /><br />
C = <input type="text" id="C" value="UUDDUUDUDUUDDUDUUUUDDDUDUUDUDUDUDDUUUUDUDUUDUDUUUDUDUDUUDUUUDUUUUUDUUDUDUUDUDUUUUUDUDUUDUDUDUDDUUUUUUUDUDUDUDUUUUUDUDUDUDUDUDUDUDUUDUUUUUURUUUDUUUUDDUUDUDUDURURURUDUDUUUUDUUUUUUDUDUDUDUDUUUUUUDUDUUUUUUUDUUUDUUDUDUDUUDUDUDUUUUUUUUUUDUUUDUDUUDUUDUUUDUUUUUUUUUUUUUDUUDUUDUDUDUUUDUDUUUUUUUDUUUDUUUDUUDUUDDUUUUUUUUDUDUDUDUDUUUUDUDUUUUUUUUDDUUDDUUDUUDUUDUDUDUDUUUUUUUUUDUUDUUDUUUDUUDUUUUUUUUUUUDUDUDUDUUUUUUUUUUUUDUUUDUUDUDDUUDUDUDUUUUUUUUUUUUDUDUDUUDUUUDUUUUUUUDUUUUUUUUUDUDUDUDUDUUUUUUDUDUDUUDUDUDUDUUUUUUUUUUUUUUUDUDUDUDDDUUUDDDDDUUUUUUUUUUUUUUDDUDUUDUUDUDUUUUUUDUDUDUDUDUUUUDUUUUDUDUDUUUDUUDDUUUUUUUUUUUUUUUUUUDUUDUUDUUUDUDUUUUUUUUUUUDUUUDUUUUDUDUDUUUUUUUUUDUUUDUUUDUUDUUUUUUUUUUUUDDUDUDUDUUUUUUUUUUUUUUUDUUUDUUUUDUUDUUDUUUUUUUUUUUDUDUUDUUUDUUUUUUDUDUDUUDUUUUUUUUUUUUDUUUDUUDUDUDUUUUDUDUDUDUDUUUUUUUUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUUU" /><br />
<button onclick="result.textContent=solution(+N.value)(C.value)">Go</button>
<pre id="result"></pre>
```
> 6 votes

# Answer
## Haskell, 65 bytes

```
x%'U'=x+1
x%'D'=max(x-1)0
x%_=0
f n=length.fst.span(<n).scanl(%)0

```

Usage example: `f 4 "UDDUURUUUUUUUDDDD"` -\> `10`.

`%` adjusts the current position on the ladder, `scanl` makes a list of all positions, `fst.span(<n)` takes the part before the explosion and `length` counts the steps.
> 4 votes

# Answer
# JavaScript (SpiderMonkey 30+), ~~65~~ 64 bytes

```
(n,s,i=0)=>[for(c of s)if(i<n)c<'E'?i&&i--:c>'T'?i++:i=0].length

```

---

### How it works

We first set the variable `i` to 0. This will keep track of how many steps the robot has climbed up. Then for each char `c` in the input string, we run the following logic:

1. If `i` is larger than or equal to `n`, don't do anything.
2. If `c` is `"D"`:
    * If `i` is 0, leave it as is.
    * Otherwise, decrement it by 1.
3. If `c` is `"U"`, increment `i` by 1.
4. Otherwise, set `i` to 0.

By cutting off if `i>=n`, we avoid adding any more items to the array after the robot has reached the top. Thus, we can simply return the length of the resulting array.
> 4 votes

# Answer
# Perl, 47 + 2 = 49 bytes

```
$z-=-/U/||$z&&/D/;$z*=!/R/;$^I<=$z&&last}{$_=$.

```

Requires the `-p` flag, `-i$N` for latter height and a newline separated list of moves:

```
$ perl -pi10 ladderbot.pl <<<< $'U\nU\nU\nU\nU\nU\nR\nU\nU\nU\nU\nU\nU\nU\nR\nU\nU\nU\nU\nU\nU\nU\nU\nR\nU\nU\nU\nU\nU\nU\nU\nU\nU\nU\nU\nU\nU\nU'
34

```

How it works:

```
                                                # '-p' wraps the code in (simplified):
                                                # while($_=<>) {...print $_}
$z-=-/U/||$z&&/D/;                              # Subtract -1 if UP. subtract 1 if DOWN
                  $z*=!/R/;                     # If R then times by zero
                           $^I<=$z&&last        # Break while loop if N is reached
                                        }{      # Eskimo operator:
                                                # while($_=<>){...}{print$_}
                                          $_=$. # `$.` contains number of lines read from input.

```

Deparsed:

```
LINE: while (defined($_ = <ARGV>)) {
    $z -= -/U/ || $z && /D/;
    $z *= !/R/;
    last if $^I <= $z;
}
{
    $_ = $.;
}
continue {
    die "-p destination: $!\n" unless print $_;
}
-e syntax OK

```
> 4 votes

# Answer
# JavaScript (ES6), 65 bytes

```
(n,s)=>[...s].map(_=>i=_<'E'?i&&i-1:_>'T'?i+1:0,i=0).indexOf(n)+1

```
> 3 votes

# Answer
## PowerShell, ~~86~~ 79 bytes

```
param($a,[char[]]$b)$b|%{$d++;if(($c-=((1,0)[!$c],-1,$c)[$_%4])-ge$a){$d;exit}}

```

A slight retooling of my When does Santa enter the basement? answer.

Takes input `$a` and `$b`, explicitly casting `$b` as char-array. We then loop with `|%{...}` over all of `$b`. Each iteration we increment our counter `$d`.

Then, an `if` statement to check whether we've hit the top with `-ge$a`. If so, we output `$d` and `exit`. The `if` statement is constructed from a pseudo-ternary created by assigning `$c` minus-equal to the result of several indexes into an array.

We have a trick that the ASCII values of `D`, `R`, and `U` correspond to `0`, `2`, and `1` when taken modulo-4, so `$_%4` serves as our first index. If it's `R`, that sets `$c` equal to `$c-$c`, doing the reset. If `U`, that means we need to go up, so the `$c-(-1)` result. Otherwise it's a `D`, so we need to check if we're already at the bottom (that's the `!$c` \- in PowerShell, "not-zero" is "true" or `1`) and set `$c` equal to `$c-0` or `$c-1` respectively.

Edit - Saved 7 bytes by using minus-equal assignment rather than direct assignment
> 3 votes

# Answer
# Perl 5, 61 bytes

Includes two bytes for `-F -i`. (`-M5.01` is free.)

Input of the integer (e.g. 10) is as `perl -M5.01 -F -i10 robot.pl`; input of the ladder commands is as STDIN.

```
for(@F){($i+=/U/)-=/R/?$i:$i&&/D/;$j++;last if$^I<=$i}say$j

```
> 3 votes

# Answer
# MATL, ~~37~~ 34 bytes

```
Oj"t@4\1=?Q}6M?x0}qt0>*]]]N$h=f1)q

```

**Try it online!**

### Explanation

Position is 0-based. Each new position is pushed onto the stack keeping the older positions. So the stack size represents the number of movements up to now, plus 1.

A loop is used to process each command. The loop ~~is exited when position reaches ladder height~~ processes all commands, even after the explosion (idea taken from Martin's answer). The final result is given by the index of the first position that equals the ladder height.

```
O             % push a 0: initial position (0-based)
j             % take first input (commands) as a string
"             % for each command
  t           %   duplicate current position
  @           %   push command
  4\          %   modulo 4. This gives 1, 2, 0 for 'U','R', 'D'
  1=?         %   if result equals 1 (command 'U')
    Q         %     increase position by 1
  }           %   else
    6M?       %     if result was nonzero (command 'R')
      x0      %       delete current position and push 0
    }         %     else (command 'D')
      q       %       decrement by 1
      t0>*    %       turn negative values into 0
    ]         %     end if
  ]           %   end if
]             % end for each
N$h           % pack all numbers in the stack into an array
=             % implicitly read second input: ladder height
f1)q          % find first position equal to that, and subtract 1.
              % Implicitly display

```
> 3 votes

# Answer
# Python 2, ~~63~~ 62 bytes

```
f=lambda n,s,h=0:h^n and-~f(n,s[1:],-[2%~h,~h,0][ord(s[0])%4])

```

For example, `f(4, 'UDDUURUUUUUUUDDDD')` is `10`.

xnor found an even shorter expression: `2%~h` is really cool :)
> 3 votes

# Answer
# Vitsy, 44 bytes

There probably could be some reductions - I'll figure out some more things if I can.

```
0vVWl:X[4M1+mDvV-);]lvXv?v-N
vD([1-]
v1+
vX0
```

Explanation (in progress):

```
0vVWl:X[4M1+mDvV-);]lvXv?v-N
0v             Save 0 as our temp var to edit.
  V            Save the input as a global var.
   W           Grab a line of STDIN.
    l          Push the length of the stack.
     :         Clone the stack. This is for later use.
      X        Remove the top item of the stack (we don't need the length right now.
[            ] Do the stuff in the brackets infinitely.
 4M            Modulo 4.
   1+          Add one.
     m         Go to the line index as specified by the top item of the stack.
      Dv       Duplicate the top item, save it in the temp var.
        V-);   If the top value is equal to the input number, exit the loop.
l              Push the length of the stack.
 vXv           Dump the temp var, then save the top item.
    ?          Rotate back to the original stack.
     v-        Subtract the top item (the original length) by the temp var (new length)
       N       Output the top item of the stack of the number.

vD([1-]
v              Push the temp variable to the stack.
 D([  ]        If this value is not zero...
    1-         Subtract one from it.

v1+            Push the temp variable to the stack, then add one to it.

vX0            Dump the temp var and replace it with zero.
```

Try It Online! (big test case)
> 3 votes

# Answer
# Python 3, 90

Saved 6 bytes thanks to DSM.

Pretty simple right now.

```
def f(c,n):
 f=t=0
 for x in c:
  f+=1|-(x<'E');f*=(x!='R')&(f>=0);t+=1
  if f>=n:return t

```

Test cases:

```
assert f('U', 1) == 1
assert f('DDRUDUU', 1) == 4
assert f('UDDUUUUURUUUUDDDD', 4) == 7
assert f('UDDUURUUUUUUUDDDD', 4) == 10
assert f('UUDDUUDUDUUDDUDUUUUDDDUDUUDUDUDUDDUUUUDUDUUDUDUUUDUDUDUUDUUUDUUUUUDUUDUDUUDUDUUUUUDUDUUDUDUDUDDUUUUUUUDUDUDUDUUUUUDUDUDUDUDUDUDUDUUDUUUUUURUUUDUUUUDDUUDUDUDURURURUDUDUUUUDUUUUUUDUDUDUDUDUUUUUUDUDUUUUUUUDUUUDUUDUDUDUUDUDUDUUUUUUUUUUDUUUDUDUUDUUDUUUDUUUUUUUUUUUUUDUUDUUDUDUDUUUDUDUUUUUUUDUUUDUUUDUUDUUDDUUUUUUUUDUDUDUDUDUUUUDUDUUUUUUUUDDUUDDUUDUUDUUDUDUDUDUUUUUUUUUDUUDUUDUUUDUUDUUUUUUUUUUUDUDUDUDUUUUUUUUUUUUDUUUDUUDUDDUUDUDUDUUUUUUUUUUUUDUDUDUUDUUUDUUUUUUUDUUUUUUUUUDUDUDUDUDUUUUUUDUDUDUUDUDUDUDUUUUUUUUUUUUUUUDUDUDUDDDUUUDDDDDUUUUUUUUUUUUUUDDUDUUDUUDUDUUUUUUDUDUDUDUDUUUUDUUUUDUDUDUUUDUUDDUUUUUUUUUUUUUUUUUUDUUDUUDUUUDUDUUUUUUUUUUUDUUUDUUUUDUDUDUUUUUUUUUDUUUDUUUDUUDUUUUUUUUUUUUDDUDUDUDUUUUUUUUUUUUUUUDUUUDUUUUDUUDUUDUUUUUUUUUUUDUDUUDUUUDUUUUUUDUDUDUUDUUUUUUUUUUUUDUUUDUUDUDUDUUUUDUDUDUDUDUUUUUUUUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUUU', 354) == 872

```
> 2 votes

# Answer
# JavaScript, ~~131~~ 106 Bytes-

I know this won't win a Code Golf competition, but this was a fun and stupid solution to implement:

```
l=>s=>Function('i=c=0;'+s.replace(/./g,x=>`c++;i${{R:"=0",U:`++;if(i>=${l})return c`,D:"--"}[x]};`))()

```

I kinda went the opposite of a "functional" route by making a dynamically-generated imperative solution, any instance of an instruction is replaced with an increment or decrement, and a counter increment.

Thanks to Cycoce for saving me 29 bytes!
> 2 votes

# Answer
# Python, 121 bytes

```
def f(a,n):
 i=c=0
 while i<n:i={'U':lambda x:x+1,'D':lambda x:0 if x==0 else x-1,'R':lambda x:0}[a[c]](i);c+=1
 return c

```
> 2 votes

# Answer
# PHP, 88 bytes

This generates some (3+2n where n is the number of commands run) notices but that doesn't matter for golfing, right?

```
<?php for(;$x++<$argv[1];)switch($argv[2][$i++]){case R;$x=2;case D;--$x?--$x:0;}echo$i;

```

ungolfed:

```
<?php                    # actually 1 byte shorter not as a function
for(;$x++<$argv[1];)     # not initialising the $x causes a notice but still works
                         # post increment $x by 1 regardless of the command (saves us writing a U case)
  switch($argv[2][$i++]) # get next command, increment number of commands
    {case R;             # R gets treated as a constant with value 'R'. and a notice
      $x=2;              # falling through to D which will double decrement so set to 2
    case D;              # same trick as R
      --$x?--$x:0;}      # decrement once then again if >0
echo$i;                  # output

```
> 2 votes

# Answer
# PHP, 129 bytes

```
function r($h,$s){$i=0;$c=1;while($x=$s[$i++]){if($x=='U'){$c++;}elseif($x=='D'){--$c<1?$c=1:0;}else{$c=1;}if($c>$h){return$i;}}}

```

Not winning, but fun to create. PHP seems to dislike empty parts in the ternary operator (it throws a Syntax Error), so I had to put a `0` there.

Ungolfed version:

```
function r($h,$s) {          // $h - height of ladder; $s - instructions
  $i = 0;                    // Instruction index
  $c = 1;                    // Position on ladder
  while ($x = $s[$i++]){     // Set $x to current instruction and increment index
    if ($x == 'U'){          // If instruction is U...
      $c++;                  // Increment ladder position
    } elseif ($x == 'D') {   // If instruction is D...
      --$c < 1 ? $c = 1 : 0; // Decrement ladder position, if under 1 set to 1
    } else {                 // If instruction is anything else (in this case R)
      $c = 1;                // Reset ladder position
    }
    if ($c > $h) {           // If ladder position is larger than height...
      return $i;             // Return current instruction index
    }
  }
}

```
> 1 votes

# Answer
# PHP, 113 bytes

Smaller version of https://codegolf.stackexchange.com/a/74575/13216

```
function r($h,$s){$i=0;$c=1;while($x=$s[$i++]){$c+=($x=='U'?1:($x=='D'?($c>1?-1:0):1-$c));if($c>$h){return $i;}}}

```

Ungolfed:

```
// $h - height of ladder; $s - instructions
function r($h,$s) {
    $i = 0;
    $c = 1;
    while ($x = $s[$i++]) {
        $c += (
            $x=='U'?
                1
            :
                (
                    $x=='D'? (
                        $c>1?
                            -1
                        :
                            0
                    ):
                        1-$c
                )
        );
        if ($c > $h) {
            return $i;
        }
    }
}

```
> 1 votes

# Answer
## Java, 250 bytes

```
int cmds(int n, String s) {
int steps=1;
int count=0;
for (int i=0;i< s.length();i++) {
count++;
char c=s.charAt(i);
switch(c){
case 'D':
steps=(steps==1)?1:--steps;
break;
case 'R':
steps=1;
break;
case 'U':
++steps;
break;
}
if(steps>n)
return count;
}
return 0;
}

```
> 1 votes

# Answer
# Mathematica, ~~114~~ 120 bytes

```
(d=#~Max~1-1&;u=#+1&;r=1&;s=StringToStream@ToLowerCase@#;l=1;t=1;While[(l=ToExpression[s~Read~Character]@l)<=#2,t++];t)&

```

Anonymous function, which takes the two arguments (C,N). Careful using this, as it doesn't close the stream it opens. Also it assigns all its variables globally.

Edited to replace `d=#-1&` with `d=#~Max~1-1&`, so that robie doesn't go digging.
> 1 votes

# Answer
# Pyth, 19 bytes

```
x.u@[tWNNhN00)CYz0Q

```

Try it online: Demonstration or Test Suite

### Explanation:

```
x.u@[tWNNhN00)CYz0Q   implicit: z = input string, Q = input number
 .u             z0    reduce z: for each char Y in z manipulate N = 0 with:
    [        )           create a list with
     tWNN                  * N-1 if N>0 else N
         hN                * N+1
           0               * 0
            0              * 0
   @          CY         replace N by the ord(Y)-th element (mod 4)
 .u                   .u give us a list with all intermediate values of N
x                 Q   print the index of Q in this list

```
> 1 votes

# Answer
# C, 91 bytes

No warnings with `gcc -Wall`. Recursion and comma-separated expressions.

`r.c` contains bare function:

```
int r(int N,int n,int s,char*C){return*C&&s<=N?s+=*C&2?-s:*C&1?1:-1,r(N,n+1,s?s:1,C+1):n;}

```

Commented,

```
int r(int N,   // number of steps on ladder
      int n,   // result, seed with 0
      int s,   // current step, seed with 1
      char *C  // command string
      )
{
    return *C&&s<=N ?  // still reading commands and still on ladder?
       s+=                // increment step value by...
        *C&2?             // bit test if 'R' but not 'U' or 'D'.
         -s               // negate to 0, will set to 1 in call if needed
         :*C&1?           // Not 'R', is it 'U'?
            1             // 'U', add 1
            :-1,          // Must be 'D', subtract 1
       r(N,n+1,s?s:1,C+1) // Recursive call, and fix case where s==0.
      :n;                 // end of string or fell off ladder
}

```

For reference,

```
'U'.charCodeAt(0).toString(2)
"1010101"
'D'.charCodeAt(0).toString(2)
"1000100"
'R'.charCodeAt(0).toString(2)
"1010010"

```

`roboladder.c` wrapper,

```
#include <stdio.h>
#include <stdlib.h>
#include "r.c"
int main(int argc, char * argv[])
{
  int N = atoi(argv[1]);
  int n = r(N,0,1,argv[2]);
  int check = atoi(argv[3]);
  printf("%d : %d\n", n, check);
  return 0;
}

```

`Makefile` for testing,

```
run:
    @gcc -Wall robotladder.c -o robotladder
    @./robotladder 1 U 1
    @./robotladder 1 DDRUDUU 4
    @./robotladder 4 UDDUUUUURUUUUDDDD 7
    @./robotladder 4 UDDUURUUUUUUUDDDD 10
    @./robotladder 6 UUUUUDRUDDDDRDUUUUUUDRUUUUUUUDR 20
    @./robotladder 10 UUUUUURUUUUUUURUUUUUUUURUUUUUUUUUUUUUU 34
    @./robotladder 6 UUUDUUUUDDDDDDDDDDDDDDRRRRRRRRRRRUUUUUU 8
    @./robotladder 6 UUUDUUUDURUDDDUUUUUDDRUUUUDDUUUUURRUUDDUUUUUUUU 32
    @./robotladder 20 UUDDUDUUUDDUUDUDUUUDUDDUUUUUDUDUUDUUUUUUDUUDUDUDUUUUUDUUUDUDUUUUUUDUDUDUDUDUUUUUUUUUDUDUUDUDUUUUU 56
    @./robotladder 354 UUDDUUDUDUUDDUDUUUUDDDUDUUDUDUDUDDUUUUDUDUUDUDUUUDUDUDUUDUUUDUUUUUDUUDUDUUDUDUUUUUDUDUUDUDUDUDDUUUUUUUDUDUDUDUUUUUDUDUDUDUDUDUDUDUUDUUUUUURUUUDUUUUDDUUDUDUDURURURUDUDUUUUDUUUUUUDUDUDUDUDUUUUUUDUDUUUUUUUDUUUDUUDUDUDUUDUDUDUUUUUUUUUUDUUUDUDUUDUUDUUUDUUUUUUUUUUUUUDUUDUUDUDUDUUUDUDUUUUUUUDUUUDUUUDUUDUUDDUUUUUUUUDUDUDUDUDUUUUDUDUUUUUUUUDDUUDDUUDUUDUUDUDUDUDUUUUUUUUUDUUDUUDUUUDUUDUUUUUUUUUUUDUDUDUDUUUUUUUUUUUUDUUUDUUDUDDUUDUDUDUUUUUUUUUUUUDUDUDUUDUUUDUUUUUUUDUUUUUUUUUDUDUDUDUDUUUUUUDUDUDUUDUDUDUDUUUUUUUUUUUUUUUDUDUDUDDDUUUDDDDDUUUUUUUUUUUUUUDDUDUUDUUDUDUUUUUUDUDUDUDUDUUUUDUUUUDUDUDUUUDUUDDUUUUUUUUUUUUUUUUUUDUUDUUDUUUDUDUUUUUUUUUUUDUUUDUUUUDUDUDUUUUUUUUUDUUUDUUUDUUDUUUUUUUUUUUUDDUDUDUDUUUUUUUUUUUUUUUDUUUDUUUUDUUDUUDUUUUUUUUUUUDUDUUDUUUDUUUUUUDUDUDUUDUUUUUUUUUUUUDUUUDUUDUDUDUUUUDUDUDUDUDUUUUUUUUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUDUUUUDUDUUUUUU 872
    @wc -c r.c

```
> 1 votes

# Answer
# Mathematica, 112 Bytes

```
i=0;First@Position[ToExpression["{"<>#~StringReplace~{"U"->"i++,","D"->"i=i~Max~1-1,","R"->"i=0,"}<>"0}"],#2-1]&

```
> 1 votes

# Answer
## Clojure, ~~92~~ 84 bytes

Counts `n` to zero instead zero to `n`, can utilize `take-while pos?`.

```
#(count(take-while pos?(reductions(fn[p o](if o(min(o p 1)%)%))%(map{\U -\D +}%2))))

```

Original:

```
#(count(take-while(partial > %)(reductions(fn[p o](if o(max(o p 1)0)0))0(map{\U +\D -}%2))))

```

Maps 2nd argument `U` to `+`, `D` to `-` and others to `nil`. Reducing function runs `(operand position 1)` with non-null `operand` and `0` otherwise. Takes values until we are higher than the 1st input argument and counts how many we've got.
> 0 votes

# Answer
# Mathematica, 67 bytes

```
(p=i=0;While[p<#,p=Switch[#2[[++i]],"U",p+1,"D",1~Max~p-1,_,0]];i)&

```

Unnamed functions of two arguments, a positive integer and a list of characters, that returns a positive integer. A more straightforward `While` implementation than the other Mathematica entries, that manages to result in a more competetive length.
> 0 votes

---
Tags: code-golf, parsing, counting
---


title: 2017 is Almost Here!

text:
# Question
Title: 2017 is Almost Here!
**Challenge**

The challenge is simple:

Taking no inputs and output the following message:

```
 _     __    __
  |   |  | |   |
  |_  |__| |   |

```

A number of times equal to the number of hours before or after midnight UTC on 31st Dec 2016.

**Examples**

For example if it is 19:01 UTC dec 31st you should output:

```
 _     __    __
  |   |  | |   |
  |_  |__| |   |
 _     __    __
  |   |  | |   |
  |_  |__| |   |
 _     __    __
  |   |  | |   |
  |_  |__| |   |
 _     __    __
  |   |  | |   |
  |_  |__| |   |
 _     __    __
  |   |  | |   |
  |_  |__| |   |

```

if it is 23:24 UTC dec 31st you should output:

```
 _     __    __
  |   |  | |   |
  |_  |__| |   |

```

and if it is 1:42 UTC jan 1st you should output:

```
 _     __    __
  |   |  | |   |
  |_  |__| |   |
 _     __    __
  |   |  | |   |
  |_  |__| |   |

```

Clarification: if it is 10-11pm dec 31st you should output two, 11-12pm dec 31st output one, 00-01am jan 1st output one, 01-02am jan 1st output two etc...

**Rules**

* No Inputs
* Trailing lines or spaces are ok.
* Your program should work any time or day I run it (albeit with a large output). For example on jan 2nd at 00:15am your code should output 25 times.

(This is my first Code Golf question so if I have left any thing important out please let me know.)

**This is Code Golf so Shortest bits win**

# Answer
# JavaScript (ES6), 107

As an anonymous method with no parameters

Note `1483228800000` is `Date.UTC(2017,0)`

```
_=>` _     __    __
  |   |  | |   |
  |_  |__| |   |
`.repeat((Math.abs(new Date-14832288e5)+36e5-1)/36e5)

```

**Test** This keeps updating every 1 minute, but you'll need a lot of patience to see the output change.

```
F=_=>`_     __    __
 |   |  | |   |
 |_  |__| |   |
`.repeat((Math.abs(new Date-14832288e5)+36e5-1)/36e5)

update=_=>O.textContent=F()

setInterval(update,60000)

update()
```

```
<pre id=O></pre>
```
> 6 votes

# Answer
# Python 2 - 97 + 17 = 114 bytes

```
import time
print'_     __    __\n |   |  | |   |\n |_  |__| |   |\n'*int((abs(time.time()-1483228800)+3599)/3600)

```

Borrowed logic for ceiling from edc65's answer.

**Python 3.5 - 116 bytes**

```
import time,math
print('_     __    __\n |   |  | |   |\n |_  |__| |   |\n'*math.ceil(abs(time.time()/3600-412008)))

```

`math.ceil` returns an integer in `3.x` whereas in `2.x` it returns a float.

Thanks elpedro for saving 3 bytes.
> 4 votes

# Answer
# C compiled with Clang 3.8.1 ~~327~~ ~~317~~ 145 Bytes

*172 bytes saved thanks to @edc65*

```
#include <time.h>
t;main(){time(&t);t=abs(difftime(t,1483228800)/3600);while(t--)puts(" _     __    __\n  |   |  | |   |\n  |_  |__| |   |\n");}

```

# Ungolfed

```
#include <time.h>
t;
main()
{
time(&t);

t=difftime(t, 1483228800)/3600;

while(t--)
    puts(" _     __    __\n  |   |  | |   |\n  |_  |__| |   |\n");
}

```

**317 bytes**

*10 bytes saved thanks to @LegionMammal978*

```
#include <time.h>
t,y,w;main() {struct tm n;time(&t);n=*localtime(&t);n.tm_hour=n.tm_min=n.tm_sec=n.tm_mon=0;n.tm_mday=1;w=n.tm_year;if((w&3)==0&&((w % 25)!=0||(w & 15)==0))w=8784;else w=8760;t=(int)difftime(t, mktime(&n))/3600;t=t<w/2?t:w-t;for(;y++<t;)puts(" _     __    __\n  |   |  | |   |\n  |_  |__| |   |\n");

```

# Ungolfed

```
#include <time.h>
t,y,w;
main()
{
    struct tm n;
    time(&t);

    n=*localtime(&t);

    n.tm_hour=n.tm_min=n.tm_sec=n.tm_mon=0;
    n.tm_mday=1;
    w=n.tm_year;

    if((w&3)==0&&((w % 25)!=0||(w & 15)==0))w=8784;else w=8760;

    t=(int)difftime(t, mktime(&n))/3600;
    t=t<w/2?t:w-t;

    for(;y++<t;)
        puts(" _     __    __\n  |   |  | |   |\n  |_  |__| |   |\n");
}

```

I will add some explanations when I'll be able to.
> 2 votes

# Answer
# Pyth \- ~~71~~ 68 bytes

```
*"_     __    __
 |   |  | |   |
 |_  |__| |   |
".Ea412008c.d0 3600

```

Uses the same logic used in my python 3.5 answer.

Try it here!
> 2 votes

---
Tags: code-golf
---


# Question
Title: Efficiently generate all vector partitions
A vector partition is splitting a vector up a series of vectors such that their sum is the original. Here are a couple partitions:

```
[3, 1, 2] = [3, 1, 2]
[3, 1, 2] = [0, 0, 1] + [0, 0, 1] + [0, 1, 0] + [1, 0, 0] + [2, 0, 0]
[3, 1, 2] = [1, 1, 2] + [2, 0, 0]

```

Here vector addition is done element-wise. A valid partition does not contain any vectors with negative integers, or the all-zero vector.

Now the challenge is to write a program or function that generates all possible vector partitions given a target vector. This may sound relatively easy...

### ...but there is a twist. If the input vector has size L, and the biggest partition it generates has M elements, you may not use more than O(L\*M) memory.

You may assume that an integer uses O(1) memory. This means that you must output the partitions as you generate them. **On top of that, you must only output each partition exactly once.** For example, these are the same partition:

```
[3, 1, 2] = [3, 0, 2] + [0, 1, 0]
[3, 1, 2] = [0, 1, 0] + [3, 0, 2]

```

If you were to output both your answer is invalid.

---

All partitions for `[3, 2]`:

```
[3, 2]
[0, 1] + [3, 1]
[0, 1] + [0, 1] + [3, 0]
[0, 1] + [0, 1] + [1, 0] + [2, 0]
[0, 1] + [0, 1] + [1, 0] + [1, 0] + [1, 0]
[0, 1] + [1, 0] + [2, 1]
[0, 1] + [1, 0] + [1, 0] + [1, 1]
[0, 1] + [1, 1] + [2, 0]
[0, 2] + [3, 0]
[0, 2] + [1, 0] + [2, 0]
[0, 2] + [1, 0] + [1, 0] + [1, 0]
[1, 0] + [2, 2]
[1, 0] + [1, 0] + [1, 2]
[1, 0] + [1, 1] + [1, 1]
[1, 1] + [2, 1]
[1, 2] + [2, 0]

```

To test your answer, run it on `[3, 2, 5, 2]`. It should generate 17939 partitions, all of which sum to `[3, 2, 5, 2]`, and that are all unique (you can test for uniqueness by first sorting each partition lexicographically).

---

Shortest code in bytes wins.

# Answer
> 3 votes
# Python 2, 289 bytes

Simple brute force algorithm. Treats entire list as a number in base `max(input)+1` (`b`), and checks each "number" in the range `[0, b**(L*M))` to see if it:

1. Sums to the correct amount
2. Is in alphabetical order (ensures uniqueness)

If the list matches these criteria, the program outputs it with all the all-zero vectors stripped.

### Memory usage

The largest data structure I use in this program is a doubly-nested list, an list length `M` containing liss length `L` to give `O(L*M)` memory.

For my other data structures, I have 3 global ints `O(3)`, 1 list length `L` (`O(L)`), 1 array length `M` (`O(M)`), and a copy of the largest array when outputting (`O(L*M)`).

In total, this gives me a memory usage of `O(2*L*M + L + M + 3)` which simplifies to `O(L*M)`, fufilling the criteria.

### Time complexity

Being a brute force algorithm, this algorithm is extremely slow. For the while loop to quit, the final int in the array needs to be `b-1`. The loop needs to run `b**(L*M)` times before that happens.

In addition, each time the list runs, it needs to check both conditions, and print the list in a worst case, using `L*M+L+M` iterations. This simplifies to give an overall `O(L*M * b**(L*M))`. I tried to test my program on `[3, 2, 5, 2]`, but gave up after 45 minutes.

### Golfed program

```
v=input()
L=len(v)
M=sum(v)
b=max(v)
R=range
t=[L*[0]for i in R(M)]
def A(l,i):
 if i<L*M-1and~-b<l[i/L][i%L]:A(l,i+1)
 l[i/L][i%L]=-~l[i/L][i%L]%-~b
while t[-1][-1]<b:
 if v==[sum(q[i]for q in t)for i in R(L)]and all(`t[i]`>=`t[i+1]`for i in R(M-1)):print[x for x in t if[0]*L!=x]
 A(t,0)

```

I might be able to golf this a bit more, especially the increment part. Ungolfed code coming.

---
Tags: code-golf, restricted-memory
---


title: Code words in integer sequences

text:
# Question
Title: Code words in integer sequences
### Introduction

*Pareidolia*: From Ancient Greek; *παρα* (*para*, “concurrent, alongside”) + *εἴδωλον* (*eídōlon*, “image”). The tendency to interpret a vague stimulus as something known to the observer, such as interpreting marks on Mars as canals, seeing shapes in clouds, or hearing hidden messages in music. Source: Wiktionary.

For example:

*Paralogia*: From Ancient Greek; *παρα* (*para*, “concurrent, alongside”) + *λόγος* (*lógos*, “speech, oration, word, ...”). The tendency to perceive words in arbitrary sequences of characters, such as in code golf programs. Source: yeah, I made that up (actually the word means something else, as pointed out by @Martin).

For example:

```
    df4$/H)hEy_^p2\
    jtK2$)look|x1$

```

### Challenge

Write a program that takes a positive integer as input, produces an integer as output, and includes an English word as part of the code. The input-output relationship must correspond to an integer sequence that can be found in OEIS.

### Rules

* Only words from this **list** are allowed. This is admittedly arbitrary, but it's essential that we all agree on which words are accepted; and in that regard this list is probably as good as any other.
* Words need to be formed by **concatenating** at least two function names or statements. If your language for example has a function called `correlation` it can't be used as is. The concatenation has to be strict: no other symbols should appear between the parts of the word. For example, `bro~ken` would not count as a word.
* **Case** is unimportant: both `valid` and `vaLiD`are acceptable.
* Words within strings do not count. The letters that make up the word need to be functions or statements in the language of choice, that is, something that is actually **executed**. For example, the following code would not be allowed: `'deoxyribonucleic'~1`, where `'...'` is a string, `~` discards the previous content, and `1` just prints number `1`.
* Every letter of the word should be **necessary**. This means that removing a single letter from the word should change the input-output relation. That includes outputting a different sequence, or outputting any other thing(s), or producing no output, or causing an error.
* Any **positive integer** should be acceptable as an input, and should produce an output, except for data-type or memory restrictions.
* The outputs corresponding to inputs `1`, `2`, `3`, ... should correspond to a sequence appearing in **OEIS**. No other output should be produced; only an integer number, possibly with trailing or leading whitespace.
* Input and output can be function arguments or stdin/stdout.

### Score

The score is computed as total code length minus twice the length of the longest word, in characters. Or equivalently, number of not-in-longest-word characters minus length of longest word.

Lowest score wins.

### Examples

Consider an imaginary postfix language that has these functions: `c`: input a number; `At`: compute square; `$`: add 1.

`cAt` would be a valid program (its output corresponds to the sequence `1`, `4`, `9`, ..., which is A000290), and it would have score −3.

`cAt$` would also be valid (sequence `2`, `5`, `10`, ..., which is A002522), with score −2.

`c$At` would not be valid, because the only word here is "At" and is produced by a single function or statement.

# Answer
# CJam, -20

```
COUNTErREVOLUTIONARIES],

```

Outputs the nth element in the sequence A010861.

```
COUNTE                      e# push values of six preinitialized variables
      r                     e# read a token of input
       REVOLUTIONARIES      e# push values of 15 other preinitialized variables
                      ]     e# wrap whole stack in array
                       ,    e# get length

```

Removing a character from the word results in a completely different sequence A010860. There is a quite interesting relationship between the two sequences: at every index n, `A010860(n)` is coprime to `A010861(n)`! There must be some deep mathematical reason behind this.

Try it here.
> 11 votes

# Answer
## CJam, -5

```
limpet;

```

A010051: prints `0` for composite numbers and `1` for primes.

It took me forever to find something that scored a few points and would break at the removal of any letter. Removing anything except `m` throws an error, and removing `m` turns the program into the identity function.

```
li  e# Read input and convert to integer.
mp  e# Check for primality.
et  e# Get current datetime as a list.
;   e# Discard the datetime again.

```

Try it online.
> 10 votes

# Answer
# 05AB1E, ~~-4~~ -11

Code, prints A010869 (constant 30):

```
ASYNcHRonouSlyI)g

```

---

Previous code:

```
DoGS

```

Explanation:

```
D     # Duplicate top of the stack
 o    # Pop a, push 2**a
  G   # For N in range(1, 2**a):
   S  # Push all chars seperate from the top of the stack

```

Prints the A010879 sequence.
> 8 votes

# Answer
# MATL, −6

```
INhale

```

**Try it online!**

Produces sequence `1`, `2`, `3`, ... (A000027)

Removing any letter changes the output, or leaves the program expecting a second input which doesn't exist, or produces an error.

### Explanation

The program simply *inhales* a number and, after some fiddling around, exhales it unchanged.

```
I    % produces number 3
N    % number of elements in stack: produces number 1
h    % concatenates horizontally into array [3, 1]
a    % true if any element is nonzero. So it gives true (or equivalently 1)
l    % produces number 1
e    % triggers implicit input and reshapes into a 1x1 array. So it leaves input unchanged

```
> 6 votes

# Answer
# Pyth, 1

```
*QhSatan0000
   Satan

```

Explanation?

```
       n00   - 0 != 0 (0)
      a   0  - abs(^-0) (0, Required so it doesn't print out a random 0)
     t       - ^-1 (-1, required or will output 0 all the time)
    a      0 - abs(^-0) (1, Required so counts in right direction, would also print out a random 0)
   S         - 1-indexed range ([1], required so next command works properly)
  h          - Get the head (if `S` missed, will out 2)
*Q           - Multiply by Q

```

1, 2, 3, 4, 5...

Sequence A000027

Subliminal messages? Never.

Try it here.
> 5 votes

# Answer
# Japt, -6

```
NuLLIFIED)r^

```

Outputs A004453: nimsum of N and 12 (N XOR 12). Test it online!

Note: the OEIS sequence is 0-indexed, so an input of 0 will result in the first item.

### How it works

```
        // Implicit: N = array of inputs
Nu      // Push the following things to N:
LLIF    // 100, 100, 64, 15,
IED     // 64 again, 14, and 13.
)r^     // Reduce by XORing (using ^ between each pair)
        // The reduction goes as follows: U, U^100, U, U^64, U^79, U^15, U^1, U^12.

```
> 4 votes

# Answer
# Headsecks, score −4

```
exit

```

This maps to the Brainfuck program `,+-.`, which reads a single character and prints it, calculating A000030. Removing any character will obviously break it.

There's also `marshal` (`,-<>+-.`), which is effectively `,-.`, but that doesn't correspond to any OEIS sequence.
> 3 votes

# Answer
# x86 machine code, score -4

Hexdump of the code:

```
53 51 55 41 53 68 69 65 73 74 51 58 83 c4 14 c3

```

Or, in code page 437:

```
SQUAShiestQXâ─¶├

```

Assembly code:

```
push ebx
push ecx
push ebp
inc ecx
push ebx
push 0x74736569
push ecx
pop eax
add esp, 0x14
ret

```

A function that adds 1 to its argument.

Removing `A` turns it into an identity function. Removing any other byte messes up the stack, causing either a crash or bad behavior of the calling function.

I am pretty sure it's possible to improve the score, but it may depend on the interpretation of the requirements. For example, using the word `SQUEAMIShness` gives a program, that increases and then decreases the `ebp` register. Does removing any of these cause a crash? A simplest test program doesn't use the `ebp` register, so maybe it doesn't... To avoid this doubt, I used a shorter word.
> 2 votes

# Answer
# Ruby, score 3

```
puts gets.partition''

```

This computes the identity sequence A000027. Output is surrounded by some whitespace; I hope that's okay.
> 1 votes

# Answer
# Math++, score -2

```
?*sine

```

Implements A000004.
> 1 votes

---
Tags: code-golf, number, word
---


title: A challenge about colours

text:
# Question
Title: A challenge about colours
Above, you can see an image full of different colours.

Click here for a hex-dump.

One possible way to generate this image is by using a linear gradient rotated 90 degrees, however, this may not be the only way.

Your task is to create a self-contained program that takes no input, and outputs an image with the same RGBA pixels as the above image, and in the exact same location, with the output image being in a file format that was created before this challenge, with the dimensions of the image being 4096x4096px, same as the original.

The shortest such program, scored in bytes, is the winner.

Cheating and standard loopholes are not allowed.

# Answer
# Processing, ~~197~~ 195 bytes

```
void setup(){size(255,255);int r=255,a=r,g=0,b=0,i,j,k;background(a);for(i=0;i<a;k=i<43?g+=6:i<85?r-=6:i<a/2?b+=6:i<170?g-=6:i<213?r+=6:a>1?b-=6:0,i++)for(j=0;j<a;point(i,j++))stroke(r,g,b,a-j);}

```

This outputs the image in a 255x255 sized window

### Explained

```
void setup(){            //this is required
  size(255,255);         //size of sketch
  int r=255,a=r,g=0,b=0,i,j,k; //declaring our vars
  background(a);         //set the background colour as white
  //for-loop for the x-coordinates, it also increments/decrements rgb values
  //  based on the x-coordinate
  for(i=0;i<a;k=i<43?g+=6:i<85?r-=6:i<a/2?b+=6:i<170?g-=6:i<213?r+=6:a>1?b-=6:0,i++)
    //for-loop for the y-coordinate (alpha)
    for(j=0;j<a;point(i,j++))   //2) then draw the point at the location
      stroke(r,g,b,a-j);        //1) set the colour of point
}

```

### Edits

* Used `int` instead of `float`
* THIS SOLUTION IS INVALID DUE TO NEW RULES BEING ADDED. I WILL UPDATE ANSWER SOON
> 3 votes

# Answer
# Python, ~~407~~ ~~404~~ 381

I just golfed the svg

```
d='<svg HBdefsTg"BS G"N:redM0YyellowM0.17Y#00ff00M0.33YcyanM0.5YblueM0.67Y#ff00ffM0.83YredM1"/B/LTw" x1Ex2Ey1Ey2="1"BS G"N:white;F:0" O"0YwhiteM1"/B/LB/defsUgVUwVB/svg>'
for R in zip("VTBUEYMNFGOHSLX",')" xEyEH/|BL id="|><|><rect fill="url(#|="0" |"/><S G"N:|;F:1" O"|S-color|S-opacity|style=|offset=|widthXheightX|stop|linearGradient|="4096" '.split('|')):d=d.replace(*R)
print d

```

A raster image can be generated using imagemagick :

```
~$ python snippet.py |convert svg:- hue.png
~$ file hue.png
hue.png: PNG image data, 4096 x 4096, 8-bit/color RGBA, non-interlaced

```
> 2 votes

# Answer
## HTML/CSS, 166 bytes

```
p{width:4096px;height:4096px;background:linear-gradient(0deg,#FFF,#FFF0),linear-gradient(90deg,red,#FF0 18.513%,lime 34.256%,aqua 50%,blue 65.43%,#F0F 81.199%,red)
```

```
<p>
```

Requires a browser that supports #RGBA colours, such as Firefox 49, Chrome 52 or Safari 9.1. I've taken the stops from the original SVG and rounded them to 5sf as that shouldn't make any difference on a 4096 pixel image, but if it does, they could be restored at a small cost. On the other hand, if rounding to either 4sf or whole pixels is OK, then that saves me a further 4 bytes.
> 1 votes

# Answer
# R, ~~95~~ ~~91~~ 88 bytes

```
frame();n=4096;for(i in 1:n){l=matrix(NA,n,n);l[,i]=1:n;image(l,a=T,c=rainbow(n,s=i/n))}

```

When creating plots in while running an R script, by default they are saved to file, either as PNG or PDF. My PC struggles creating the 4096x4096 pixel plot taking up gigs of RAM, but if I change `n` to `256` it matches the correct output.

There are probably some bytes to be saved by making the arguments of `image` shorter, but I'll look at that when I get the supposed output.
> 1 votes

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


title: Animate tacky light decorations

text:
# Question
Title: Animate tacky light decorations
This challenge is in honor of the tacky Christmas lights at my in laws' house.

---

**The challenge is to create a graphical output showing the decoration in "real time".**

The video (gif or other format) will have **n-by-m** vertical and horizontal "lights". **5 \<= m,n \<= 40**. The frame size and resolution may vary dependent on **n** and **m**, but must be at least **50x50** pixels for **n,m=5** (vector graphics is OK). A picture with `n=6` and `m=5` will look something like this:

---

## The decoration:

**Colors:**

All lights will have one of the following 6 RGB-colors `{255,0,0}`, `{0,255,0}`, `{0,0,255}`, `{255,255,0}`, `{0,255,255}` and `{255,0,255}`.

**Animation:**

* `n` and `m` will be taken as input on any reasonable format and in the order you like
* The image will change every `dt = 25 ms`. Deviations are OK if it's due to "outside factors" such as limitation in the interpreter, slow computer etc.
    + If it's *impossible* to set the time step manually, then the default time step is accepted.
* All lights will be red (`{255,0,0}`) at `t=0`.
* There's always a 5% chance that the first light (top-left) will change color. All colors (except the color it currently has) should be equally likely.
* Each light (except the first) will get the color of the light to its left. If the light is at the far left then it will get the color of the light on the far right on the row above. The lights are numbered as shown below. Light number `k` will get the color of the light number `k-1`.

```
 1  2  3  4  5  6
 7  8  9 10 11 12
13 14 15 16 17 18

```
* The output should in theory run for ever (unless your language / interpreter has some limitation that prevents this).
* Please provide a sample of at least 5 seconds, preferably more in the answer (this is an encouragement, not a requirement). (A link to TIO or similar is of course OK too :D )
* Frames, axes, grid lines etc are accepted.

**6-by-5**

**15-by-30**

# Answer
# MATLAB, ~~255~~ 210 bytes

This is my first golf, so there are probably improvements to be made.

Thanks to Luis for helping me save 45 bytes :)

```
function f(n,m)
c=dec2bin(1:6)-48;r=1;p=c(r,:);x=zeros(1,n*m,3);x(:,:,1)=1;while 1
x=circshift(x,[0,1,0]);if rand>0.94;r=randi(6);end
x(1,1,:) = c(r,:);imagesc(permute(reshape(x,n,m,3),[2 1 3]));pause(1/40);end

```

**Explanation:**

```
c=dec2bin(1:6)-48  % c is the colormap
r=1;p=c(r,:);                % p is color number r (starting at 1) from the colormap c
x=zeros(1,n*m,3);x(:,:,1)=1; % 2D matrix in the third dimension. The first layer is 1
while 1                      % while true
x=circshift(x,[0,1,0]);      % shift the vector horizontally along the second dimension
if rand()>0.94;              % 5 percent chance of changing color
k=randperm(6);k=k(k~=r);r=k(1); % Create a vector with color numbers 1..6. Discard the current color, and choose the first color
x(1,1,:) = c(r,:);           % The first light gets color number r
imagesc(permute(reshape(x,n,m,3),[2 1 3]));  % Reshape the vector so that it's a 3D matrix
% Permute it so that the dimensions are correct
% Use imagesc to display
pause(1/40)  % 0.025 seconds pause

```

Unfortunately, this doesn't save the animation, it just runs it. In order to save it I either need a screen capture program, or rewrite it all using `imwrite`. Instead, I'll provide two pictures showing different times, for `n=15,m=30`.
> 6 votes

# Answer
# Mathematica, ~~186~~ ~~161~~ 158 bytes

```
(b=Table[{1,0,0},1##];Dynamic@Image[Partition[Pause@.025;If[Random[]<.06,b[[1]]={1,1,0,0}~RandomSample~3];b=RotateRight@b;b[[1]]=b[[2]];b,#],ImageSize->50#])&

```

**Explanation**

```
b=Table[{1,0,0},1##];

```

Create the initial board in 1D, filled with red. Store that in `b`.

```
Pause@.025

```

Pause for 25ms

```
If[Random[]<.06,b[[1]]={1,1,0,0}~RandomSample~3]

```

If a (pseudo-)random real number is less than 0.06, replace the first element of `b` with a random sample length `3` of the list `{1,1,0,0}`. (i.e. any one of `{1, 1, 0}, {1, 0, 1}, {1, 0, 0}, {0, 1, 1}, {0, 1, 0}, {0, 0, 1}`)

```
b=RotateRight@b

```

Cyclic rotate right.

```
b[[1]]=b[[2]]

```

Change the first cell value to the second cell value (i.e. undo the shift of the first cell)

```
Partition[ ... ;b,#]

```

Partition `b` into (height).

```
Dynamic@Image[ ... ,ImageSize->50#]

```

Make that into a dynamic (constantly updating) image, whose width is 50(width)

**Cellular automaton version (186 bytes)**

```
(b=Table[{1,0,0},1##];Dynamic@Image[Partition[Pause@.025;If[Random[]<.06,b[[1]]={1,1,0,0}~RandomSample~3];i=2;b={#[[2-Boole[i--<0],2]]&,{},{1,1}}~CellularAutomaton~b,#],ImageSize->50#])&

```

**Sample Output** (inputs: 16, 10)
> 6 votes

# Answer
## JavaScript/CSS/HTML, 436 bytes

```
b="red"
f=_=>{o.textContent='';o.style.width=w.value*10+"px";o.style.height=h.value*10+"px"}
setInterval(_=>o.insertBefore(document.createElement("s"),o.firstChild).style.background=b=["red","yellow","lime","aqua","blue","fuchsia"][Math.random()*100|0]||b,25)
```

```
#o{overflow:hidden;background:red}s{display:block;float:left;width:10px;height:10px}
```

```
<div oninput=f()><input id=h type=number min=1><input id=w type=number min=1></div><div id=o>
```
> 6 votes

# Answer
# MATL, ~~52~~ 47 bytes

```
6:BoHZGKipY"`tGe!2YG50Yr3>?t1)}6Yr]0(1YS.015Y.T

```

Input is an array `[ncols nrows]`. Output is a figure with vector graphics.

Example run for 15 cols × 10 rows:

### How it works

Pause time has been set to 15 ms (for the same byte count as 25 ms) to try compensate for the processing time.

To keep the color with 19/20 probability (change it with 1/20), we proceed as follows:

* With 47/50 probability we keep the color.
* With 3/50 probability we pick a new color choosen uniformly among the 6 colors. It may happen that the "new" color is the same as the old, and this occurs with probability 1/6.

Thus the probability of keeping the color is 47/50 + 3/(50\*6) = 19/20.

```
6:        % Push [1 2 3 4 5 6]
B         % Convert to binary. This gives a 6×3 matrix, where each row
          % corresponds to a number. First row is [0 0 1] (blue), second is
          % [0 1 0] (green), etc
o         % Convert to double
HZG       % Set as colormap (creates a figure)
K         % Push 4
i         % Take input array
p         % Product of array. This gives the total number of squares
Y"        % Repeat 4 that many times. This gives a row vector representing the
          % image. The initial value, 4, corresponds to red in the colormap
`         % Do...while
  t       %   Duplicate
  Ge      %   Reshape to size given by the input. Gives a matrix where each
          %   entry  will be interpreted as a pointer to the colormap
  !       %   Transpose. This is required because the color shifting will be
          %   done in column-major order: down, then across; whereas we want
          %   the opposite
  2YG     %   Show matrix as image using the defined colormap
  50Yr    %   Push a uniformly distributed random integer between 1 and 50
  3>      %   True if greater than 3. This happens with probability 47/50
  ?       %   If true
    t1)   %     Duplicate and get first entry (to repeat the first color)
  }       %   Else
    6Yr   %     Push a uniformly distributed random integer between 1 and 6.
          %     This is the new color (possibly the same as the old)
  ]       %   End
  0(      %   Assign that color (repeated or new) to the last entry of the row
          %   vector representing the image
  1YS     %   Circularly shift to the right. The last value becomes the first
 .015Y.   %   Pause 0.015 ms
 T        %   Push true
          % End (implicit). Since the top of the stack is true, this creates
          % an infinite loop

```
> 4 votes

# Answer
# MATLAB, ~~153~~ 147 bytes

**Note**: The GIF shown is of the older version, which is nice as it does not display axes (see edit history), but was *extremely* slow due to the implementation of `imshow`. For the current version, Chelsea G.'s MATLAB answer or Luis Mendo's MATL answer show the same result as my current version.

Size is taken as a `2x1` vector, so call as e.g.:

```
>> l([5 5])

```

---

```
function l(s)
c=eye(3);x=eye(s);while 1
a=rand>.94;x=[a*randi(6)+~a*x(1),x(1:end-1)];imagesc(reshape(x,s)',[1,6]);colormap([c;1-c])
pause(.025)
end

```

This answer exploits the subtleties of the MATLAB language. For example, `x` is initalized as an `m x n` zero matrix, but so-called *linear indexing* allows for circular shifting with 1-dimensional indices. Weak typing allows for multiplication with logicals, so that `if` statements are avoided (a trick I heavily used back in the days of programming on a TI-84 calculator). Even though a colormap is read row-wise, MATLAB treats it as a normal matrix, so that `eye(3)` can be used to create red, green and blue, and `1-eye(3)` the other three colours. A simple `reshape` brings the linear vector back into matrix form, which is mapped to the desired colours using `ind2rgb`. Finally, `imagesc`, shows the image, shown at default figure size (which is big enough for the requirements). As luck would have it, `imagesc` does not mind values being outside the specified range, so `eye` can be used to initialize the matrix since both `1` and `0` are considered red.
> 3 votes

# Answer
# Python 3.6 (316 Bytes)

Using ANSI colour codes and the new formatted string literals of Python 3.6 (PEP 489) (the `f"{X}"` magic).

Otherwise it’s just pretty basic, but obfuscated python. Width and Height are passed as arguments on the command line.

```
import random as n,time,sys
r=range
X="\x1b["
C=[f"{X}1;4{x}m " for x in r(1,7)]
w,h=list(map(int,sys.argv[1:]))
a=[C[0]for i in r(w*h)]
while 1:
 print(f"{X}0m{X}2J{X}f");f=a[0];a.pop();a[:0]=n.choice([x for x in C if x!=f])if n.random()<=.05 else f,
 for i in r(0,h*w,w):print(*a[i:i+w],sep="")
 time.sleep(.025)

```
> 2 votes

---
Tags: code-golf, random, animation
---