Wednesday, December 02, 2026

Advent of Code 2016 - Day 25: Clock Signal

Part 1

Description

The input is a program for the same little computer as in Days 12 and 23, with one more instruction, out x, which sends the value of x as a signal. Part 1 asks for the lowest positive number to put in register a so that the program sends the signal 0, 1, 0, 1, 0, 1, … forever. 

Solution

I didn't run the program, I read it. It has two parts.

Lines 1 to 8 start with cpy a d. Then two nested loops add 1 to d a certain number of times: the first loop repeats 633 times, and the outer one repeats 4 times (the numbers on lines 2 and 3 of my program). So at the end d is a + 4 × 633, which is a + 2532.

Lines 9 to 30 are an endless loop:

  1. Copy d into a.
  2. Divide a by 2 (the loops count how many times 2 fits into it) and send the remainder with out. The remainder is the lowest binary digit.
  3. Do step 2 again with the quotient, until it is 0.
  4. Start again from the top with d.

So the program sends the binary digits of d, lowest digit first, over and over.

For the signal to be 0, 1, 0, 1, …, the binary digits of d have to alternate, with a 0 at the bottom and a 1 at the top: 10, 1010, 101010 and so on, which are the numbers 2, 10, 42, 170, 682, 2730, … Which numbers have alternating digits? The one with n digits is the number with all n digits set, 2^n − 1, minus the alternating number with n − 1 digits. So in a table, H is n, I is 2^n − 1, and J is I minus the previous J:

H3: =SEQUENCE(20,,0)
I3: =POWER(2,H3)-1
J3: 0
J4: =I4-J3            ← fill down to J22

J then reads 0, 1, 2, 5, 10, 21, 42, 85, 170, … and only the even numbers end in a 0, so only those start the signal with 0.

Because a has to be at least 1, d is at least 1 + 2532. So d is the first even number in column J that is larger than 2532, and a is that number minus 2532:

P10: =4*633
O10: =LET(j,J3:J22,MIN(FILTER(j,(j>P10)*ISEVEN(j))))
O11: =O10-P10

O11 is the answer. To check it, put the value in register a and run the program in the interpreter from Day 12 or Day 23: the signal alternates 0, 1, 0, 1, … In one-cell formula, it will look like:

=LET(
 input, $A$4:$A$33,
 split, TEXTSPLIT(TEXTJOIN("|",1,input)," ","|",),
 fac_1, --INDEX(split,2,2),
 fac_2, --INDEX(split,3,2),
 mul, fac_1*fac_2,
 sq, SEQUENCE(20,,0),
 jac, (2^(sq+2)-3-(-1)^sq)/6,
 MIN(FILTER(jac,(jac>mul)*ISNUMBER(jac)*(MOD(jac,2)=0)))-mul
)

Part 2

Description

There is no puzzle for the second star on Day 25. It is given automatically once all the other stars have been collected.


Share:

Sunday, November 29, 2026

Advent of Code 2016 - Day 24: Air Duct Spelunking

Part 1

Description

A robot has to go through a maze of walls (#) and open spaces (.). Some open spaces have a number, 0 to 7 in my maze. The robot starts at 0, and Part 1 asks for the fewest steps that take it to every number at least once, in any order. 

Solution

I split this into two smaller problems. First, find the shortest walking distance between every two numbered locations. There are only 28 pairs of the 8 locations. After that, the maze isn't needed any more, and what remains is a small "which order should I visit them in" problem: 7 locations after the start can be visited in 7! = 5,040 orders. Excel can just try all of them.

The distances. Using the name manager, I created a BFS lambda function to count the distance between two places. It looks at all the cells one step away from the start, then two steps away, and so on, and never walks into #. It remembers where each cell was reached from, so when it finds the goal it can walk back to count the steps:

=LAMBDA(grid,sx,sy,tx,ty,LET(w,COLUMNS(grid),h,ROWS(grid),dirs,{0,-1;-1,0;1,0;0,1},tg_keys,ty*1000+tx,start,HSTACK(sx,sy,0,-1),result,REDUCE(start,SEQUENCE(w*h),LAMBDA(state,lev,LET(keys,INDEX(state,,2)*1000+INDEX(state,,1),IF(SUM(--ISNUMBER(XMATCH(keys,tg_keys)))>0,state,LET(frontier,FILTER(state,INDEX(state,,3)=lev-1,HSTACK(-1,-1,-1,-1)),IF(INDEX(frontier,1,1)=-1,state,LET(candidates,DROP(REDUCE(HSTACK(0,0,0,0),SEQUENCE(ROWS(frontier)),LAMBDA(acc,i,LET(x,INDEX(frontier,i,1),y,INDEX(frontier,i,2),pk,y*1000+x,nx,x+CHOOSECOLS(dirs,1),ny,y+CHOOSECOLS(dirs,2),VSTACK(acc,HSTACK(nx,ny,EXPAND(lev,4,1,lev),EXPAND(pk,4,1,pk)))))),1),cand_keys,INDEX(candidates,,2)*1000+INDEX(candidates,,1),valid,MAP(SEQUENCE(ROWS(candidates)),LAMBDA(i,LET(x,INDEX(candidates,i,1),y,INDEX(candidates,i,2),k,INDEX(cand_keys,i),IF(OR(x<0,x>=w,y<0,y>=h),FALSE,AND(INDEX(grid,y+1,x+1)<>"#",ISNA(XMATCH(k,keys)),XMATCH(k,cand_keys)=i))))),fresh,FILTER(candidates,valid,HSTACK(-1,-1,-1,-1)),IF(INDEX(fresh,1,1)=-1,state,VSTACK(state,fresh))))))))),final_keys,INDEX(result,,2)*1000+INDEX(result,,1),hits,FILTER(result,ISNUMBER(XMATCH(final_keys,tg_keys)),HSTACK(-1,-1,-1,-1)),IF(INDEX(hits,1,1)=-1,"Nopath",LET(steps,INDEX(hits,1,3),path,REDUCE(INDEX(hits,1,{1,2,3,4}),SEQUENCE(steps),LAMBDA(acc,s,LET(pk,INDEX(acc,1,4),prev,FILTER(result,final_keys=pk),VSTACK(prev,acc)))),steps))))

grid is the excel representation of the input, using: 

=LET(
 input, A5:A45,
 grid, MID(input, SEQUENCE(, MAX(LEN(input))), 1), 

sx, sy, tx and ty are starting points and target points. 

All the orders. For the 5,040 orders I used a formula, like below. The perms parts puts 0 in front of 1234567, etc. 

=LET(
 input, A5:A45,
 grid, MID(input, SEQUENCE(, MAX(LEN(input))), 1),
 numb, IFERROR(--grid, grid),
 highest, MAX(numb),
 rrr, SEQUENCE(ROWS(grid), , 0),
 ccc, SEQUENCE(, COLUMNS(grid), 0),
 pts, SORT(HSTACK(
  TOCOL(IF(ISNUMBER(numb), numb, NA()), 2),
  TOCOL(IF(ISNUMBER(numb), ccc, NA()), 2),
  TOCOL(IF(ISNUMBER(numb), rrr, NA()), 2)
 )),
 nnn, SEQUENCE(highest + 1, , 0),
 comb, FILTER(TOCOL(nnn & TRANSPOSE(nnn)), TOCOL(nnn < TRANSPOSE(nnn))),
 dist, MAP(comb, LAMBDA(pair,
  LET(
   aaa, --LEFT(pair, 1) + 1,
   bbb, --RIGHT(pair, 1) + 1,
   BFSa(numb, INDEX(pts, aaa, 2), INDEX(pts, aaa, 3), INDEX(pts, bbb, 2), INDEX(pts, bbb, 3))
  )
 )),
 perms, "0" & REDUCE("", SEQUENCE(highest), LAMBDA(acc,k,
  TOCOL(IFS(ISERROR(FIND(SEQUENCE(, highest), acc)), acc & SEQUENCE(, highest)), 2)
 )),
 steps, MID(perms, SEQUENCE(, highest), 2),
 norm, IF(LEFT(steps, 1) < RIGHT(steps, 1), steps, RIGHT(steps, 1) & LEFT(steps, 1)),
totals, BYROW(INDEX(dist, XMATCH(norm, comb)), LAMBDA(row, SUM(row))),
MIN(totals)
)

Part 2

Description

Now the robot has to go back to location 0 at the end. The question is the fewest steps for the whole trip. 

Solution

For each route I also need the distance from its last location back to 0. In V46 I typed 0, and W46 looks up the distance between the last location and V46. The total then includes this extra step, and the answer is the shortest of all the totals, or by adapting my formula, adding  0 in the perms part.

 

Share:

Advent of Code 2016 - Day 23: Safe Cracking

Part 1

Description

This is the little computer from Day 12 with one more instruction, tgl x, which changes the program while it runs. It toggles the instruction that is x lines away from itself:

  • An instruction with one argument becomes dec if it was inc, and inc in every other case.
  • An instruction with two arguments becomes cpy if it was jnz, and jnz in every other case.
  • If the line is outside the program, nothing happens.

Register a starts at 7, and Part 1 asks which value is in a when the program ends.

Solution

Because the program can change, the program itself has to be part of the state. I kept it as a column of 26 lines (A5:A30), with the five numbers of the machine next to the first line: the registers a, b, c, d and step, the number of the next line (B5:F5, with their names in B4:F4). One iteration of a REDUCE executes one instruction, just like in Day 12, and one extra thing happens when the instruction is tgl: the toggled line is replaced in the program column.

B2: =LET(
 input, A4:A29,
 regs, {"a","b","c","d","step"},
 aa, {7,0,0,0,1},
 init, HSTACK(input,aa),
 c, REDUCE(init,SEQUENCE(70000),
  LAMBDA(p,q,LET(
   step, INDEX(p,1,6),
   ins, TEXTSPLIT(INDEX(p,step,1)," "),
   ra, INDEX(ins,,2),
   rb, INDEX(ins,,3),
   stepconst, {0,0,0,0,1},
   reg, TAKE(DROP(p,,1),1),
   vala, XLOOKUP(ra,regs,reg,--ra),
   valb, XLOOKUP(rb,regs,reg,--rb),
   lf, INDEX(p,,1),
   tgl, SUM({0,0,1,0,0}*reg),
   tri, MID(INDEX(lf,tgl+step),1,3),
   lft, IF(
    OR(INDEX(ins,,1)<>"tgl",tgl+step>ROWS(input)),lf,
     IF(vala=0,VSTACK(TAKE(lf,step-1),"inc "&MID(INDEX(lf,tgl+step),5,10),DROP(lf,step)),
      IF(LEN(INDEX(lf,tgl+step))<6,VSTACK(TAKE(lf,tgl+step-1),
       IF(tri="inc","dec "&MID(INDEX(lf,tgl+step),5,10),"inc "&MID(INDEX(lf,tgl+step),5,10)),DROP(lf,tgl+step)),VSTACK(TAKE(lf,tgl+step-1),
        IF(tri="jnz","cpy ","jnz ")&MID(INDEX(lf,tgl+step),5,10),DROP(lf,tgl+step)))
     )
   ),
   inst,SWITCH(INDEX(ins,,1),
    "cpy",IF(regs=rb,vala,reg)+stepconst,
    "inc",IF(regs=ra,reg+1,reg)+stepconst,
    "dec",IF(regs=ra,reg-1,reg)+stepconst,
    "jnz",IF(vala=0,stepconst,stepconst*valb)+reg,
    "tgl",stepconst+reg
   ),
   rs,IF(step>ROWS(input),p,HSTACK(lft,TAKE(inst,1))),
   rs
   )
  )
 ),
 CHOOSECOLS(TAKE(c,1),2)
)
  • The registers part works exactly as in Day 12: inst computes the new registers for cpy, inc, dec and jnz, and for tgl only the step goes up.
  • tgl reads register c in my program, and the toggled line is step + c.
  • If the instruction is tgl and the line is in the program, lft is the program with that one line replaced. If c is 0 the instruction toggles itself, which becomes an inc. A line with one argument is short (inc a is 5 characters), and inc becomes dec while everything else becomes inc. A longer line has two arguments: jnz becomes cpy, and everything else becomes jnz.
  • When step goes past line 26 the program has ended, and nothing changes any more. At the end, the second column of the first row, register a, is the answer.

Part 2

Description

The number of eggs is really 12, and the question is the same. The program multiplies, and with 12 eggs it takes billions of instructions, far too many for a formula. 

Solution

First I ran the program for small numbers of eggs, and looked at the registers each time the program starts a new round (at line 4). The numbers have a clear pattern: a and d hold a running product, b counts down by one each round, and c is -16. For 12 eggs the running product goes 12, 12 × 11, 12 × 11 × 10 and so on, up to 12!. The table in H66:L77 lists that pattern.

So I didn't need to run those rounds. I jumped straight to the state where the last round is done: a is 12!, b is 2, c and d are 0, and the next line is line 10. By then the program has toggled three of its own lines, and in G33:G58 I wrote the program as it looks after that, with the registers in H33:L33. The remaining part of the program, the two loops that add a fixed amount to a, is short: fewer than 50,000 instructions. So the same interpreter finishes the job from there:

D2: =LET(aa,G33:L58,
         cc,$B$32:$F$32,
         c,REDUCE(aa,SEQUENCE(50000),LAMBDA(p,q, ... )),     ← the same formula as in B2
         CHOOSECOLS(TAKE(c,1),2))

To be sure, the same idea with 7 eggs gives the 13776 of Part 1. And since the program ends by adding the product of two numbers, which are on two lines of my input, the answer is 12! plus that product, which is another way to check it.

Share:

Friday, November 27, 2026

Advent of Code 2016 - Day 22: Grid Computing

Part 1

Description

The input is the output of a df -h command on a grid of storage nodes. Every line gives the node's position (x and y), its size, how much is used, how much is available, and the percentage used. Part 1 asks for the number of viable pairs of nodes (A, B): A is not empty, A and B are not the same node, and the data on A would fit in the available space of B. 

Solution

I pasted the 957 lines into A7:A963. The first thing is to turn every line into numbers. TEXTSPLIT cuts a line at the text that surrounds the numbers (/dev/grid/node-x, -y, spaces, T and %) and ignores empty pieces, and -- makes them numbers. A REDUCE does this for every line and stacks the results, and DROP removes the starting empty row:

b: DROP(REDUCE("",SEQUENCE(ROWS(A7:A963)),LAMBDA(x,y,
      IFNA(VSTACK(x,--TEXTSPLIT(INDEX(A7:A963,y,1),{"/dev/grid/node-x";"-y";" ";"T ";"%"},,TRUE)),""))),1)

This is a table with six columns: x, y, size, used, avail and use%. The same formula in B7 spills it onto the sheet, in B7:G963.

For the pairs, I compare every node A that isn't empty with every node B. us>0 marks the non-empty nodes, and us<=TRANSPOSE(av) is true where A's used space is at most B's available space. The first SUMPRODUCT counts these for all pairs, including A = B, and the second one subtracts the pairs where a node would fit its own data:

B2: =LET(
 a, A7:A963,
 b, DROP(REDUCE("",SEQUENCE(ROWS(a)),
  LAMBDA(x,y,
   IFNA(VSTACK(x,--TEXTSPLIT(INDEX(a,y,1),{"/dev/grid/node-x";"-y";" ";"T ";"%"},,TRUE)),"")
  )
 ),1),
 x, INDEX(b,,1),
 y, INDEX(b,,2),
 sz, INDEX(b,,3),
 us, INDEX(b,,4),
 av, INDEX(b,,5),
 pe, INDEX(b,,6),
 c,SUMPRODUCT((us>0)*(us<=TRANSPOSE(av)))-SUMPRODUCT((us>0)*(us<=av)),
 c
)

Part 2

Description

Now I want to move the data. Data can only be moved from a node to a neighbouring one (up, down, left or right), and all of it at once. The goal is the data in the top-right node, and I want to bring it to the top-left node, where I can get it. Part 2 asks for the fewest moves. 

Solution

For this one I looked at the grid and solved it by hand. First I drew the grid on the sheet. H7 holds a key for each node (=B7*100+C7), the x positions are in row 6 and the y positions in column I, and every cell shows the size and the used space of its node:

J7: =INDEX($D$7:$D$963,MATCH(J$6*100+$I7,$H$7:$H$963,0))&"/"&
     INDEX($E$7:$E$963,MATCH(J$6*100+$I7,$H$7:$H$963,0))

Looking at the picture:

  • Almost all nodes have a similar size and use about the same amount of space. The data of any node fits in the free space of only one node, the empty one. There is exactly one empty node.
  • One row of nodes has so much data that it can never move. It forms a wall across the grid, with a gap at the left end.

So this is a sliding puzzle with one empty tile, and the only thing that moves is the empty node. Moving the empty node onto a neighbour moves that neighbour's data into it. I counted the moves in three parts:

  1. Take the empty node to the top-left corner, going through the gap in the wall.
  2. Move it along the top row until it is next to the goal data, and then one more move to swap places with it. Now the goal data is one step to the left, with the empty node on its right.
  3. Every further step of the goal data to the left takes 5 moves: the empty node goes down, left, left and up to get in front of the data, and then right to swap places with it. That is 5 moves for every position, until the data reaches the corner.
D2: =LET(
 input, A7:A963,
 split, DROP(REDUCE("",SEQUENCE(ROWS(input)),
  LAMBDA(x,y,
   IFNA(VSTACK(x,--TEXTSPLIT(INDEX(input,y,1),{"/dev/grid/node-x";"-y";" ";"T ";"%"},,TRUE)),"")
  )
 ),1),
 x, INDEX(split,,1),
 y, INDEX(split,,2),
 sz, INDEX(split,,3),
 us, INDEX(split,,4),
 av, INDEX(split,,5),
 pe, INDEX(split,,6),
 Part1,REDUCE(0, SEQUENCE(ROWS(input)),
  LAMBDA(p,q,
   LET(
    u, INDEX(us, q),
    a, INDEX(av, q),
    p + SUM(--(FILTER(us, us>0) <= a)) - --((u>0)*(u<=a))
   )
  )
),
 grid, WRAPCOLS(us,SUM(--(x=0))),
 tx, MAX(x),
 ty, MIN(y),
 r, SEQUENCE(ROWS(grid), 1, 0),
 c, SEQUENCE(1, COLUMNS(grid), 0),
 marked, IF((r=ty)*(c=tx), CHAR(64), grid),
 path, BFSa(marked,tx,ty,MIN(x),MIN(y)),
 init_state, VSTACK(marked, HSTACK(0, EXPAND("", 1, COLUMNS(grid)-1, ""))),
 move2, REDUCE(init_state, SEQUENCE(ROWS(path)-1), LAMBDA(k,l,
  LET(
   curr_grid, DROP(k, -1),
   curr_moves, INDEX(k, ROWS(k), 1),
   idx, MATCH(0, TOCOL(curr_grid), 0) - 1,
   czero, MOD(idx, COLUMNS(grid)),
   rzero, QUOTIENT(idx, COLUMNS(grid)),
   path0, BFSa(curr_grid, INDEX(path, l+1, 1), INDEX(path, l+1, 2), czero, rzero),
   move, REDUCE(curr_grid, SEQUENCE(ROWS(path0)-1),
    LAMBDA(p,q,
     LET(
      xa, INDEX(path0, ROWS(path0)+1-q, 1),
      ya, INDEX(path0, ROWS(path0)+1-q, 2),
      xb, INDEX(path0, ROWS(path0)-q, 1),
      yb, INDEX(path0, ROWS(path0)-q, 2),
      va, INDEX(p, ya+1, xa+1),
      vb, INDEX(p, yb+1, xb+1),
      IF((r=ya)*(c=xa), vb, IF((r=yb)*(c=xb), va, p))
     )
    )
   ),
   next_grid, IF((r=INDEX(path, l, 2))*(c=INDEX(path, l, 1)), 0,
    IF((r=INDEX(path, l+1, 2))*(c=INDEX(path, l+1, 1)), "@", move)
   ),
   next_moves, curr_moves + ROWS(path0),
   VSTACK(next_grid, HSTACK(next_moves, EXPAND("", 1, COLUMNS(grid)-1, "")))
  )
 )),
 Part2, INDEX(move2, ROWS(move2), 1),
 Part2
)
Share:

Wednesday, November 25, 2026

Advent of Code 2016 - Day 21: Scrambled Letters and Hash

Part 1

Description

A password is scrambled by a list of operations: swap two positions, swap two letters, rotate left or right by some steps, rotate based on the position of a letter, reverse part of the password, or move one letter to another position. The input is the list of operations, one per line, and Part 1 asks what the password abcdefgh becomes. 

Solution

I pasted the 100 operations into A5:A104 and put the starting password in B4. One formula applies them one after another with REDUCE, and p is the password so far. For each operation it needs three things:

  • The kind of operation, from the first nine characters of the line, because they are different for every kind (swap posi, swap lett, reverse p, rotate le, rotate ri, move posi and rotate ba).
  • The numbers in the line, e. For each digit from 0 to 9 I look for its position in the line, keep the ones found, sort them, and read the characters. Positions are single digits, because the password has 8 letters.
  • The letters in the line, f. The letters follow the word "letter", which ends in r, so I look for r a, r b and so on, and take the character after it.

Then SWITCH picks the right operation:

<
B2: =LET(
 a, $A$5:$A$104,
 b, LEFT(a,9),
 c, REDUCE("abcdefgh",SEQUENCE(ROWS(a)),
  LAMBDA(p,q,
   LET(
    d, INDEX(a,q),
    e, --MID(d,SORT(FILTER(FIND(SEQUENCE(10,,0),d),ISNUMBER(FIND(SEQUENCE(10,,0),d)))),1),
    f, MID(d,SORT(FILTER(FIND("r "&CHAR(SEQUENCE(10,,97)),d)+2,ISNUMBER(FIND("r "&CHAR(SEQUENCE(10,,97)),d)+2))),1),
    g, MID(p,INDEX(e,1)+1,1),
    x, SWITCH(INDEX(b,q),
     "swap posi",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(p,g,"_"),MID(p,INDEX(e,2)+1,1),g),"_",MID(p,INDEX(e,2)+1,1)),
     "swap lett",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(p,INDEX(f,1),"_"),INDEX(f,2),INDEX(f,1)),"_",INDEX(f,2)),
     "reverse p",CONCAT(MID(p,1,INDEX(e,1)),TEXTJOIN("",1,MID(MID(p,INDEX(e,1)+1,INDEX(e,2)+1-INDEX(e,1)),{10,9,8,7,6,5,4,3,2,1},1)),MID(p,INDEX(e,2)+2,LEN(p)-INDEX(e,2)-1)),
     "rotate le",CONCAT(MID(p,1+INDEX(e,1),LEN(p)-INDEX(e,1)),MID(p,1,INDEX(e,1))),"rotate ri",CONCAT(MID(p,LEN(p)-INDEX(e,1)+1,INDEX(e,1)),MID(p,1,LEN(p)-INDEX(e,1))),
     "move posi",CONCAT(MID(SUBSTITUTE(p,g,""),1,INDEX(e,2)),g,MID(SUBSTITUTE(p,g,""),INDEX(e,2)+1,LEN(p))),
     "rotate ba",LET(a,FIND(INDEX(f,1),p),b,IF(a<5,CONCAT(MID(p,LEN(p)-a+1,a),MID(p,1,LEN(p)-a)),CONCAT(MID(p,LEN(p)+1-MOD(a+1,LEN(p)),MOD(a+1,LEN(p))),MID(p,1,LEN(p)-MOD(a+1,LEN(p))))),b)
    ),
    x
   )
  )
 ),
 c
)
  • Swaps. I swap two letters through a temporary _ character.
  • Reverse. I cut out the part to reverse and read its letters backwards, using the index list {10,9,…,1}. The 1 in TEXTJOIN ignores the empty results for positions past its end.
  • Rotations. A left rotation moves the first n letters to the end, and a right rotation moves the last n letters to the front.
  • Move. I take the letter out, and put it back after the first e2 letters that remain.
  • Rotate based on a letter. The rotation is right by 1 plus the position of the letter (counting from 0), plus 1 more if the position is 4 or more. With a = position + 1, that is a steps when a is below 5, and a + 1 steps otherwise (wrapping around the 8 letters).

For the puzzle's example, the password abcde with the example's eight operations becomes decab.

Part 2

Description

Now I know the scrambled password, fbgdceah (typed in D4), and I need the original password that the same operations turned into it. 

Solution

I use the same formula with three changes. First, the operations are applied in reverse order. A5:A104 is sorted by line number from the last line to the first, and the first column is kept:

a: TAKE(SORT(HSTACK($A$5:$A$104,SEQUENCE(ROWS($A$5:$A$104))),2,-1),,1)

Second, every operation is undone by its opposite:

  • Swaps and reverses undo themselves.
  • Rotating left is undone by rotating right, and the other way around. That is why the "rotate le" and "rotate ri" branches are swapped.
  • move position X to position Y is undone by moving the letter that is now at position Y back to position X:
"move posi",CONCAT(MID(SUBSTITUTE(p,MID(p,INDEX(e,2)+1,1),""),1,INDEX(e,1)),
                   MID(p,INDEX(e,2)+1,1),
                   MID(SUBSTITUTE(p,MID(p,INDEX(e,2)+1,1),""),INDEX(e,1)+1,LEN(p)))

Third, the hard one: undoing rotate based on position of letter X. How far the password was rotated depends on where the letter was before, but I can tell from where it is now. For 8 letters each position gives a different answer. For a letter now at position 0 to 7, the password must be rotated left by 1, 1, 6, 2, 7, 3, 0 and 4 (or right by 7, 7, 2, 6, 1, 5, 0 and 4) to undo it. The formula computes the right rotation b from the position a of the letter:

"rotate ba",LET(a,FIND(INDEX(f,1),p),
                b,MOD(8-a+IF(MOD(a,2)=0,MOD(a+6,8),IF(a=1,a+13,a+5))/2+1,8),
                CONCAT(MID(p,LEN(p)-b+1,b),MID(p,1,LEN(p)-b)))

Everything else is the same as in Part 1, with $D$4 as the starting password. In the end I scrambled the result again with Part 1's formula to check that I got fbgdceah back.

Share:

Tuesday, November 24, 2026

Advent of Code 2016 - Day 20: Firewall Rules

Part 1

Description

A firewall blocks IP addresses, written as numbers from 0 up to 4,294,967,295 (the largest 32-bit number). The input is a list of blocked ranges like 5-8, which blocks everything from 5 to 8, including both ends. The ranges may overlap. Part 1 asks for the lowest number that isn't blocked.  

Solution

I pasted the 1,104 ranges into A5:A1108, one per line, as text. The first step turns them into a table of numbers with one range per row. TEXTJOIN joins all the lines into one text with _ between them, and TEXTSPLIT cuts it into rows at every _ and into columns at every -. The -- changes the text into numbers. Then I sort the table by the start of each range:

b: --TEXTSPLIT(TEXTJOIN("_",,A5:A1108),"-","_")
c: SORT(b,1)

Then I walk through the sorted ranges and keep a candidate, p: the lowest IP not blocked so far, starting at 0. For each range:

  • If the candidate is lower than the start of the range, nothing blocks it, and the later ranges start even higher, so it stays.
  • Otherwise the range reaches the candidate, and I move the candidate to just after the end of the range (or keep it if that's lower).
B2: =LET(
 a, A5:A1108,
 b, --TEXTSPLIT(TEXTJOIN("_",,a),"-","_"),
 c, SORT(b,1),
 d, REDUCE(0,SEQUENCE(ROWS(a)),
  LAMBDA(p,q,
   IF(q=1,(INDEX(c,q,2)+1+p),IF(p<INDEX(c,q,1),p,MAX(INDEX(c,q,2)+1,p)))
  )
 ),
 d
)

For the puzzle's example, the blocked ranges 5-8, 0-2 and 4-7 leave 3 as the lowest allowed number.

Part 2

Description

How many IPs are allowed in total, from 0 up to 4,294,967,295? 

Solution

I use the same sorted table and walk through it again. This time the state has two numbers: how many allowed IPs I have counted, and the highest blocked IP so far (it starts at -1). For each range:

  • The IPs between the highest blocked IP and the start of this range are allowed. That is start − highest − 1, or none if the range overlaps.
  • Then the highest blocked IP becomes the larger of the old one and this range's end.

At the end, the IPs above the highest blocked one, up to 4,294,967,295, are allowed too:

D2: =LET(
 a, SORT(--TEXTSPLIT(TEXTJOIN("_",,$A$5:$A$1108),"-","_"),1),
 b, ROWS(a),
 c, SEQUENCE(b),
 d, REDUCE({0,0}, c,
  LAMBDA(p,q,
   LET(
    fr, INDEX(a,q,1),
    to, INDEX(a,q,2),
    mx, INDEX(p,,2),
    bl, MAX(fr-mx,0),
    su, HSTACK(INDEX(p,,1)+IF(bl>1,1,0),MAX(mx,to)),
    su
   )
  )
 ),
 e, DROP(d,,-1),
 e
)

For the puzzle's example, with 9 as the highest IP instead of 4,294,967,295, this gives 2.

Share:

Advent of Code 2016 - Day 19: An Elephant Named Joseph

Part 1

Description

A number of elves sit in a circle, each with one present. Starting with elf 1, each elf in turn takes all the presents of the elf on their left, and that elf is out of the game. This goes around the circle until one elf is left, and Part 1 asks which elf that is. My puzzle input is the number of elves, in A4.  

Solution

This is a famous puzzle (the Josephus problem), and it has a closed formula. Write the number of elves as the largest power of 2 that is not more than it, plus a remainder r. With exactly a power of 2 elves, elf 1 always wins. With r extra elves, after the first r steals the circle has exactly a power of 2 elves left, and the elf whose turn it is, number 2r + 1, is in the same position as elf 1 was, so that elf wins:

B2: =2*(A4-POWER(2,ROUNDDOWN(LOG(A4,2),0)))+1

The puzzle's example with 5 elves gives elf 3.

Part 2

Description

The rule changes: each elf now takes the presents from the elf directly across the circle. Which elf gets all the presents? 

Solution

I didn't see a closed formula at first, so I looked at how the winner changes when the circle grows by one elf. I simulated small circles and found this rule. Let w be the winner for n − 1 elves and let d be n divided by 2, rounded down. For n elves the winner is w + 1 if w is less than d, and w + 2 otherwise, and if that goes past n it wraps around to the start. For one or two elves the winner is elf 1. To check the rule, I also simulated the circle itself with arrays for some small cases (including 10,000 elves).

REDUCE repeats the rule for every number of elves, with p the winner so far and q the number of elves:

E4: =LET(a,1,
 b,SEQUENCE(D4),
 c,REDUCE(a,b,
  LAMBDA(p,q,
   LET(
    d,ROUNDDOWN(q/2,0),
    e,IF(OR(q=1,q=2),1,
     IF(p<d,p+1,
      IF(p+2>q,MOD(p+2,q),p+2))),
    e
   )
  )),
 c
)

Doing three million steps in one formula is too heavy, so I split the work into chunks of a million. D4 holds the size of a chunk (1,000,000), and D5, D6 and D7 hold where the next chunks start. E4 gives the winner for a million elves. E5 starts from E4 and continues from 1,000,001 up to 2,000,000, and E6 continues to 3,000,000:

E5: =LET(a,E4,b,SEQUENCE(D4,,D5), ...)          ← the same rest of the formula
E6: =LET(a,E5,b,SEQUENCE(D4,,D6), ...)

The last chunk covers the remaining elves, from 3,000,001 up to my input (C7: =A4-D7+1 is how many that is):

D2: =LET(a,E6,b,SEQUENCE(C7,,D7), ...)          ← the same rest of the formula

For the puzzle's example, 5 elves, the answer is elf 2.

A shortcut. There is also a closed formula for Part 2, with powers of 3. Take the largest power of 3 that is below the number of elves, k. If the number of elves n is at most 2k, the winner is n − k, and otherwise it is 2n − 3k:

=LET(n,A4,k,POWER(3,ROUNDDOWN(LOG(n-1,3),0)),IF(n<=2*k,n-k,2*n-3*k))

It gives the same answer as the chunked formula, instantly.

Share:

Recent Posts

Coba Kalau Berani

Blog Archive

Categories