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:

Advent of Code 2016 - Day 18: Like a Rogue

Part 1

Description

A room is made of rows of tiles, each either safe (.) or a trap (^). The first row is my puzzle input. Every other row is worked out from the row above: a tile is a trap if its left, centre and right neighbours above are (trap, trap, safe), (safe, trap, trap), (trap, safe, safe) or (safe, safe, trap), and it's safe otherwise. Beyond the two ends of a row, the tiles count as safe. Part 1 asks for the number of safe tiles in the first 40 rows. 

Solution

I put my input in A4, and cut it into single tiles in the first row of the grid:

L7: =MID(A4,SEQUENCE(,LEN(A4)),1)        ← fills L7:DG7 (100 tiles)

Every tile below that looks at the three tiles above it. This is the formula for L8, written out with the four rules from the puzzle, and I filled it right and down to row 46 (40 rows in all):

L8: =IF((K7="^")<>(M7="^"),"^",".")

The two edges are taken care of by the columns next to the grid. Column K holds the row numbers 1 to 40 (K7: =SEQUENCE(40)), and a number is not a ^, so it counts as a safe tile on the left. The empty column after the last tile is the safe tile on the right. The answer is the number of safe tiles in the whole grid:

B2: =COUNTIF(L7:DG46,".")

The puzzle's small example (.^^.^.^^^^ for 10 rows) gives the 38 safe tiles from the puzzle text.


Part 2

Description

Now the room has 400,000 rows, and Part 2 asks for the safe tiles again. 

Solution

Drawing 400,000 rows of 100 tiles would take 40 million cells, so I only keep the row I am working on. First, look at the four rules again: the middle tile never matters. A tile is a trap exactly when its left and right neighbours are different. If I write safe as 1 and a trap as 0, then a new tile is 1 when the two neighbours are equal, and 0 when they differ. At the ends of the row, the missing neighbour is safe (1).

The formula keeps one row of numbers: the first number is the running total of safe tiles, and the 100 after it are the current row. REDUCE repeats the step 399,999 times (the first row, plus 399,999 more, makes 400,000):

D2: =LET(
 a, SUBSTITUTE(SUBSTITUTE(A4,".",1),"^",0),
 b, --MID(a,SEQUENCE(,LEN(a)),1),
 s, SUM(b),
 c, REDUCE(HSTACK(s,b),SEQUENCE(399999),
  LAMBDA(p,q,
   LET(
    d, SEQUENCE(,LEN(a)),
    e, IF(d=1,INDEX(TAKE(p,-1,-LEN(a)),,d+1),
     IF(d=LEN(a),INDEX(TAKE(p,-1,-LEN(a)),,d-1),
      IF(INDEX(TAKE(p,-1,-LEN(a)),,d-1)<>INDEX(TAKE(p,-1,-LEN(a)),,d+1),0,1)
    )),
    f, TAKE(p,-1,1)+SUM(e),
    g,HSTACK(f,e),
    g
   )
  )
 ),
 TAKE(c,,1)
)
  • a turns the input into 1s (safe) and 0s (traps), b is the first row as numbers, and s is how many safe tiles it has.
  • TAKE(p,-1,-LEN(a)) is the current row (the last 100 numbers), and e is the next row. The first tile equals its right neighbour, because its left neighbour is the safe edge. The last tile equals its left neighbour. Every other tile is 0 if its two neighbours differ and 1 if they are equal.
  • f adds the safe tiles of the new row to the running total, and HSTACK(f,e) is the new state.
  • At the end, TAKE(c,,1) is the running total.

With only 39 repeats instead of 399,999 the same formula gives the answer to Part 1.

Share:

Monday, November 23, 2026

Advent of Code 2016 - Day 17: Two Steps Forward

Part 1

Description

I have to get from the top-left room of a 4 × 4 grid to the vault in the bottom-right room. Every room has four doors, up, down, left and right. Whether a door is open depends on the MD5 hash of my puzzle input (the passcode) followed by the path taken so far (for example UDR). The first four characters of the hash say if the doors up, down, left and right are open, and b, c, d, e or f means open. The edge of the grid is a wall. Part 1 asks for the shortest path to the vault. 

Solution

The passcode is in A5. The 16 rooms are in G6:J9, and each cell holds its own address as text (G6, H6, and so on, up to J9), which makes moving between rooms easy. The border of # characters is only decoration.


MD5 isn't built into Excel, so I used the same MD5 VBA function as in the earlier posts, saved as an Excel add-in (md5.xlam), and call it as MD5Hash.

I found the shortest path with a breadth-first search done in one formula. The state is the passcode plus the path so far, together with the current room. I pust my passcode and starting room (G6) ini A5 and B5. The input is those value. One step takes every state and works out which doors are open, which room each door leads to, and drops the moves that would leave the grid. The new states are the old path plus the direction letter, with the new room. A REDUCE repeats the step up to 30 times, and it stops as soon as one state is in room J9, the vault:

B2: =LET(
 input, $A$5:$B$5,
 rd, REDUCE(input, SEQUENCE(100),
  LAMBDA(acc, nn,
   IF(OR(INDEX(acc, , 2) = "J9"), acc,
    DROP(REDUCE(0, SEQUENCE(ROWS(acc)), LAMBDA(p, q,
     LET(
      a, $G$6:$J$9,
      b, TOCOL(ADDRESS(ROW(a), COLUMN(a), 4)),
      c, {"U", -1, 0; "D", 1, 0; "L", 0, -1; "R", 0, 1},
      hs, INDEX(acc, q, 1),
      sp, INDEX(acc, q, 2),
      md, hs & TAKE(c, , 1),
      hsh, ISNUMBER(FIND(MID(LOWER(MD5Hash(hs)), SEQUENCE(4), 1), "bcdef")),
      dir, ADDRESS(ROW(INDIRECT(sp)) + INDEX(c, , 2), COLUMN(INDIRECT(sp)) + INDEX(c, , 3), 4),
      mddir, FILTER(HSTACK(md, dir), hsh * IFNA(POWER(XMATCH(dir, b), 0), 0) = 1, ""),
      IF(INDEX(mddir, 1, 1) <> "", VSTACK(p, mddir), p)
     )
    )), 1)
   )
  )
 ),
 MID(XLOOKUP("J9", INDEX(rd, , 2), INDEX(rd, , 1)), 1 + LEN(INDEX(input, , 1)), 99)
)
  • c is a table of the four directions and how each one changes the row and the column.
  • md is the four new paths (the old path with U, D, L and R added).
  • hsh is TRUE for each direction whose door is open: the first four hash characters, each looked up in "bcdef".
  • dir is the address of the room next to the current one in each direction, and XMATCH(dir,b) checks that the address is one of the 16 rooms, so moves outside the grid are dropped.
  • mddir keeps only the open and valid moves, and VSTACK adds them to the new list, which starts with a dummy 0 that DROP removes.
  • The last line takes the first state that reached J9 and cuts the passcode off the front, which leaves the path. Because it is a breadth-first search, that path is a shortest one.

The three examples in the puzzle text (ihgpwlah, kglvqrro and ulqzkmiv) give the shortest paths from the puzzle.

Part 2

Description

Now I want the length of the longest path to the vault. A path ends when it reaches the vault, so it can't go through it and out again. 

Solution

I couldn't make my formula find this by itself. So another formula. It remembers the longest one:

B4: =LET(
 seed, A5,
 c, {"U",-1,0;"D",1,0;"L",0,-1;"R",0,1},
 init, VSTACK({"",0,0,0}, HSTACK(seed,1,1,0)),
 res, REDUCE(init, SEQUENCE(450),
  LAMBDA(acc,nn,
   LET(
    best, INDEX(acc, 1, 4),
    IF(ROWS(acc)=1, acc,
     LET(
      next_raw, REDUCE({"",0,0,0}, SEQUENCE(ROWS(acc)-1, 1, 2),
       LAMBDA(p,q,
        LET(
         r, INDEX(acc, q, 2),
         col, INDEX(acc, q, 3),
         IF((r=4)*(col=4), p,
          LET(
           hs, INDEX(acc, q, 1),
           md, hs & TAKE(c,,1),
           hsh, ISNUMBER(FIND(MID(MD5Hash(hs), SEQUENCE(4), 1), "bcdef")),
           nr, r + INDEX(c,,2),
           nc, col + INDEX(c,,3),
           valid, hsh * (nr>=1) * (nr<=4) * (nc>=1) * (nc<=4),
           mddir, FILTER(HSTACK(md, nr, nc, {0;0;0;0}), valid=1, {"",0,0,0}),
           IF(INDEX(mddir, 1, 1)="", p, VSTACK(p, mddir))
          )
         )
        )
       )
      ),
      IF(ROWS(next_raw)=1,
       HSTACK("", 0, 0, best),
       LET(
        next_gen, DROP(next_raw, 1),
        hit, SUM((INDEX(next_gen,,2)=4) * (INDEX(next_gen,,3)=4)),
        new_best, IF(hit>0, nn, best),
        VSTACK(HSTACK("", 0, 0, new_best), next_gen)
       )
      )
     )
    )
   )
  )
 ),
 INDEX(res, 1, 4)
)

It visits about 36,000 rooms, so it needs about as many MD5 hashes. The number of moves of the longest path is the answer.

Share:

Sunday, November 22, 2026

Advent of Code 2016 - Day 16: Dragon Checksum

Part 1

Description

To fill a disk with random-looking data, I start with my puzzle input, a string of 0s and 1s, and keep making it longer. Each round takes the data a, makes a reversed copy b with every 0 and 1 swapped, and the new data is a, then a 0, then b. I do that until there is enough data and then cut it to the size of the disk. The checksum comes from pairing up the characters: a pair of equal characters gives 1, a pair of different characters gives 0. I repeat on the result until its length is odd. Part 1 asks for the checksum for a disk of a given size. 

Solution

The input is in A6 and the disk size is in A5. One formula in B2 does everything.

How many rounds? With an input of length n, each round doubles the length plus one: after c rounds the length is (n + 1) · 2^c − 1. So the number of rounds I need is:

round: ROUNDDOWN(LOG(ROUNDDOWN((size+1)/(LEN(input)+1),0),2),0)+1

One round. The reversed copy is made by reading the characters from the last to the first (MID with a SEQUENCE that counts down). To swap 0 and 1 without mixing them up, I change 1 to 2, then 0 to 1, then 2 to 0:

CONCAT(p,0,SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(CONCAT(MID(p,SEQUENCE(LEN(p),,LEN(p),-1),1)),1,2),0,1),2,0))

The checksum. Each round halves the length, and I stop when it is odd. The number of rounds is how many times 2 divides the disk size (for example, 272 = 16 × 17 gives 4 rounds). In each round a pair gives NOT(XOR(…)), which is 1 for equal bits and 0 for different ones. Each REDUCE adds the new bits to the end of the text it started with, so the checksum is the last third of the final text. The whole formula:

B2: =LET(
 input, A6,
 size, A5,
 round, ROUNDDOWN(LOG(ROUNDDOWN((size+1)/(LEN(input)+1),0),2),0)+1,
 full, REDUCE(input,SEQUENCE(round),
  LAMBDA(p,q,
   CONCAT(p,0,SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(CONCAT(MID(p,SEQUENCE(LEN(p),,LEN(p),-1),1)),1,2),0,1),2,0)
   )
  )
 ),
 trunc, MID(full,1,size),
 fit, REDUCE(size,SEQUENCE(10,,10,-1),LAMBDA(p,q,LET(r,IF(MOD(p,POWER(2,q))=0,p,MOD(p,POWER(2,q))),r))),
 logs, LOG(fit,2),
 hasil, REDUCE(trunc,SEQUENCE(logs),
  LAMBDA(p,q,
   LET(
    k, RIGHT(p,size/(POWER(2,q-1))),
    l, REDUCE(k,SEQUENCE(LEN(k)/2),
     LAMBDA(r,s,
      LET(
       m, CONCAT(r,--NOT(XOR(--MID(r,s*2-1,1),--MID(r,s*2,1)))),
       m
      )
     )
    ),
    l
   )
  )
 ),
 n, RIGHT(hasil,LEN(hasil)/3),
 n
)

f finds the largest power of 2 that divides the disk size, and g is how many halvings that is. The puzzle's example (input 10000, disk size 20) gives 01100.

Part 2

Description

The disk is now much bigger, 35,651,584 characters. A cell holds at most 32,767 characters, so I can't even build the data, and I need a smarter way. 

Solution

The data has a pattern. After 10 rounds my 17-character input has become one block of 18,431 characters, which I call D. Q2 is D, and Q3 is the reverse of D with 0 and 1 swapped. The whole endless data then goes: D, one separator character, D reversed and swapped, one separator, D, one separator, and so on. The odd positions alternate between Q2 and Q3, and the even positions are single separator characters:

Q2: =LET(
 input, A6,
 round, 10,
 full, REDUCE(input,SEQUENCE(round),
  LAMBDA(p,q,
   CONCAT(p,0,SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(CONCAT(MID(p,SEQUENCE(LEN(p),,LEN(p),-1),1)),1,2),0,1),2,0)
   )
  )
 ),
 full
)
Q3: =SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(CONCAT(MID(Q2,SEQUENCE(LEN(Q2),,LEN(Q2),-1),1)),1,2),0,1),2,0)

The separators follow the same dragon rule. The separator at position i is 0 if i is a power of 2, and otherwise it is the opposite of the separator at position (the next power of 2 above i) − i. In row 6, with the positions 1, 2, 3 and so on in row 4 (E4: =SEQUENCE(,4096)):

E6: =IF(MOD(E4,4)=1, $Q$2,
 IF(MOD(E4,4)=3, $Q$3,
  IF(E4=POWER(2,ROUNDDOWN(LOG(E4,2),0)),0,
   --NOT(INDEX($E$6:E6,POWER(2,1+ROUNDDOWN(LOG(E4,2),0))-E4))
  )
 )
)

The checksum can be done in pieces. The disk size is 17 × 2^21, so the final checksum has 17 characters, and every one of them comes from a block of 2^21 characters. The first 11 rounds of pairing can therefore be done separately on pieces of 2,048 characters. A block D plus its separator is 18,432 characters, which is exactly 9 × 2,048, so it shrinks to 9 characters after 11 rounds. Row 8 does the first round for each such pair (the odd column together with the next one), and rows 9 to 18 do the next ten:

E8: =IF(MOD(E4,2)=1,RIGHT(REDUCE(CONCAT(E6:F6),SEQUENCE(LEN(CONCAT(E6:F6))/2),
       LAMBDA(r,s,LET(m,CONCAT(r,--NOT(XOR(--MID(r,s*2-1,1),--MID(r,s*2,1)))),m))),
       LEN(CONCAT(E6:F6))/2),"")
E9: =IF(MOD(E$4,2)=1,RIGHT(REDUCE(E8,SEQUENCE(LEN(E8)/2),
       LAMBDA(r,s,LET(m,CONCAT(r,--NOT(XOR(--MID(r,s*2-1,1),--MID(r,s*2,1)))),m))),
       LEN(E8)/2),"")

(RIGHT(…,LEN/2) keeps only the newly added bits.) I filled these across and down. 1,934 pairs cover 35,647,488 characters. The last 4,096 characters come from the start of the next block, which gives 2 more bits, so that column uses LEFT(ERY6,4096) instead of the whole block. All the 9-bit pieces joined together give 17,408 bits:

E19: =CONCAT(E18:ERY18)

The last 10 rounds work on this one string (17,408 → 8,704 → … → 17), one row each:

E20: =RIGHT(REDUCE(E19,SEQUENCE(LEN(E19)/2),
       LAMBDA(r,s,LET(m,CONCAT(r,--NOT(XOR(--MID(r,s*2-1,1),--MID(r,s*2,1)))),m))),
       LEN(E19)/2)

E29 has 17 characters, and that is the answer:

E2: =E29

Share:

Recent Posts

Categories

Blog Archive