Tuesday, November 24, 2026

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:

Advent of Code 2016 - Day 15: Timing is Everything

Part 1

Description

A capsule is dropped through a stack of spinning discs. Each disc has a hole at position 0, and the discs rotate one position every second. The capsule needs one second to fall from one disc to the next, so it has to reach disc number k at the moment that disc's hole is at position 0. Part 1 asks for the first time I can press the button so that the capsule falls through every disc. 

Solution

From each line of the input I put the input into: the disc number, how many positions it has, and where it is at time 0:

B5: =LET(
 tokens, DROP(REDUCE("", A5:A10, LAMBDA(acc,cell, VSTACK(acc, TEXTSPLIT(cell, {" ";".";"#"}, , TRUE)))), 1),
 nums, TOCOL(IFERROR(NUMBERVALUE(tokens), "")),
 WRAPROWS(FILTER(nums, nums<>""),3)
)

If I press the button at time t, the capsule reaches disc k at time t + k. At that moment the disc is at position (t + k + its start position) modulo (its number of positions), and that has to be 0, for every disc.

After the product of all the disc sizes, every disc is back where it started, so the pattern repeats. That means the answer is somewhere between 0 and that product, and I can check all of those times at once:

B4: =LET( d,SEQUENCE(,6),
 a,SEQUENCE(PRODUCT(C5:C10),,0),
 b,d+a+TRANSPOSE(D5:D10),
 c,MOD(b,TRANSPOSE(C5:C10)),
 INDEX(a,MATCH(6,MMULT(N(c=0),{1;1;1;1;1;1}),0)))
)
  • d is the disc numbers 1 to 6, and a is every time to try.
  • b is a table with one row per time and one column per disc, holding t + k + start. c is the position of each disc when the capsule reaches it.
  • N(c=0) makes a table of 1s where the disc is at position 0. MMULT adds up each row. A row with a total of 6 has all six discs at 0, and MATCH finds the first such row.

With the puzzle's example, two discs with 5 positions at position 4 and 2 positions at position 1, the answer is 5.

Part 2

Description

A new disc with 11 positions, starting at position 0, is added at the bottom. The question is the same.

Solution

The same formula now has seven columns, and the table would have to cover the product of all seven sizes, which is far too big for Excel. Instead I searched a window of a million times at a time, and the answer turned out to be in the one starting at 3,000,000:

D2: =LET(
 d,SEQUENCE(,7),
 a,SEQUENCE(1000000,,3000000,1),
 b,d+a+TRANSPOSE(D5:D11),
 c,MOD(b,TRANSPOSE(C5:C11)),
 INDEX(a,MATCH(7,MMULT(N(c=0),{1;1;1;1;1;1;1}),0))
)

A shortcut. The first six discs line up again every "product of the six sizes" seconds, so the answer for seven discs must be Part 1's answer plus a whole number of those steps. The new disc has 11 positions, so at most 11 steps need to be tried:

=LET(t,B2+B13*SEQUENCE(C11,,0),INDEX(t,MATCH(0,MOD(t+B11+D11,C11),0)))

Here B13 is the product of the six sizes. It gives the same answer, without searching millions of rows.


Share:

Advent of Code 2016 - Day 14: One-Time Pad

Part 1

Description

The hash of my puzzle input (the salt) followed by a number is an MD5 hash written in hex. A number is a one-time pad key when its hash has some character three times in a row (only the first such triplet counts), and one of the next 1,000 hashes has the same character five times in a row. Part 1 asks for the number that gives the 64th key. 

Solution

MD5 isn't built into Excel, so I used the same MD5Hash VBA function as in Day 4 AoC 2015. Source and credit goes there. The salt is in A5. 

Stage 1: collect the interesting hashes. First, I join the salt with numbers 1 to 30,000, and find the MD5hash for each. If a hash contains a triplet, a row (triplet, number, hash) is added; the list starts with a row of zeros:

A6: =LET(
 salt, $A$5,
 max_idx, 100,
 hex, MID("0123456789abcdef", SEQUENCE(16), 1),
 triplets, REPT(hex, 3),
 quints, REPT(hex, 5),
 idx, SEQUENCE(max_idx, , 0),
 hashes, MAP(idx, LAMBDA(i, MD5Hash(salt & i))),
 first_trip_char, MAP(hashes, LAMBDA(h, LET(
  pos, MIN(IFERROR(FIND(triplets, h), 99)),
  IF(pos < 99, MID(h, pos, 1), "")
 ))),
 quint_chars, MAP(hashes, LAMBDA(h,
  TEXTJOIN("", TRUE, IF(ISNUMBER(FIND(quints, h)), hex, ""))
 )),
 is_valid, MAP(idx, first_trip_char, LAMBDA(i,ch,
 IF(ch = "", FALSE,
  SUM((idx > i) * (idx <= i + 1000) * ISNUMBER(FIND(ch, quint_chars))) > 0
  )
 )),
 valid_keys, FILTER(idx, is_valid),
 HSTACK(FILTER(first_trip_char, first_trip_char<>""),FILTER(idx, first_trip_char<>""),FILTER(hashes, first_trip_char<>""))
)

Stage 2: find the keys. Changing the last line of above formula with:

 HSTACK(FILTER(quint_chars, quint_chars<>""),FILTER(idx, quint_chars<>""),FILTER(hashes, quint_chars<>""))

and I get the quintets, For each hash with a five-in-a-row, I look at the triplet hashes in the previous 1,000 numbers. There is a catch: a hash can contain more than one triplet, and only the leftmost one counts. It can be done by changin the last line of above formula:

INDEX(valid_keys, 64)

For the puzzle's example salt abc the answer is 22728.

Part 2

Description

Now each hash is computed with key stretching: after the first MD5 of the salt and number, the resulting hex text is hashed again, 2,016 more times. Everything else stays the same. 

Solution

On Part 2, the formulas are the same, except that the hash line becomes a second REDUCE of 2,017 steps (the 2,016 re-hashes and the first hash), and I go up to 26,000 numbers.

That is about 52 million hashes, so this sheet takes a very long time to calculate. Stage 2 is the same formula as above, and the answer is again the 64th entry of the sorted list:

D2: =LET(
 salt, $A$5,
 max_idx, 100,
 hex, MID("0123456789abcdef", SEQUENCE(16), 1),
 triplets, REPT(hex, 3),
 quints, REPT(hex, 5),
 idx, SEQUENCE(max_idx, , 0),
 hashes, MAP(idx, LAMBDA(i, REDUCE(MD5Hash(salt & i),SEQUENCE(2016,,0),LAMBDA(r,s,MD5Hash(r))))),
 first_trip_char, MAP(hashes, LAMBDA(h, LET(
  pos, MIN(IFERROR(FIND(triplets, h), 99)),
  IF(pos < 99, MID(h, pos, 1), "")
 ))),
 quint_chars, MAP(hashes, LAMBDA(h,
  TEXTJOIN("", TRUE, IF(ISNUMBER(FIND(quints, h)), hex, ""))
 )),
 is_valid, MAP(idx, first_trip_char, LAMBDA(i,ch,
 IF(ch = "", FALSE,
  SUM((idx > i) * (idx <= i + 1000) * ISNUMBER(FIND(ch, quint_chars))) > 0
  )
 )),
 valid_keys, FILTER(idx, is_valid),
 INDEX(valid_keys, 64)
)

For the example salt abc the answer is 22551.

Share:

Advent of Code 2016 - Day 13: A Maze of Twisty Little Cubicles

Part 1

Description

An office building is laid out as an endless grid of squares, each either a wall or an open space. Whether the square at position (x, y) is a wall comes from a formula. Take x·x + 3x + 2xy + y + y·y, add my puzzle input (the "favorite number"), and write the result in binary. If it has an odd number of 1s, the square is a wall, and if it has an even number, the square is open. I start at (1, 1), and Part 1 asks for the fewest steps to reach (31, 39). 

Solution

First I built the maze. My puzzle input is in A4. The x positions 0 to 99 run across row 5, and the y positions 0 to 99 run down column E:

F5: =SEQUENCE(,100,0)
E6: =SEQUENCE(100,,0)

Then every square gets the formula from the puzzle. BASE(…,2) writes the number in binary, SUBSTITUTE removes the zeros, LEN counts the ones, and MOD(…,2) gives 1 for an odd count (wall) and 0 for an even one (open):

F6: =LET(
 input, A4,
 xx, SEQUENCE(,100,0),
 yy, SEQUENCE(100,,0),
 sum, LAMBDA(y,x, x*x + 3*x + 2*x*y + y + y*y+input)(yy,xx),
 grid, MOD(LEN(SUBSTITUTE(BASE(sum,2),"0","")),2),
 grid
 )

It spilled over F6:DA105 (100 × 100 squares) and added conditional formatting so the walls show up. The square (x, y) is in column F + x and row 6 + y, so the start (1, 1) is G7 and the goal (31, 39) is AK45.

 

To find the shortest route I used a breadth-first search. It visits the start, then everything one step away, then everything two steps away, and so on, so the first time it reaches the goal is by a shortest route. For every square it remembers where it came from, so afterwards it can walk back from the goal to the start. It also keeps the distance of every square, which Part 2 needs. I put the BFS in the name manager:

=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),
  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)),
       IF(
        INDEX(frontier,1,1)=-1,
        state,
        LET(
         candidates,DROP(REDUCE(HSTACK(0,0,0),SEQUENCE(ROWS(frontier)),
          LAMBDA(acc,i,
           LET(
            x,INDEX(frontier,i,1),
            y,INDEX(frontier,i,2),
            nx,x+CHOOSECOLS(dirs,1),
            ny,y+CHOOSECOLS(dirs,2),
            VSTACK(acc,HSTACK(nx,ny,EXPAND(lev,4,1,lev)))
           )
          )
         ),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)=0,ISNA(XMATCH(k,keys)),XMATCH(k,cand_keys)=i)
           )
          )
         )),
         fresh,FILTER(candidates,valid,HSTACK(-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)),
  IF(INDEX(hits,1,1)=-1,-1,INDEX(hits,1,3))
 )
)

The number of steps is the number of squares in the path list:

B2: =LET(
 input, A4,
 xx, SEQUENCE(,100,0),
 yy, SEQUENCE(100,,0),
 sum, LAMBDA(y,x, x*x + 3*x + 2*x*y + y + y*y+input)(yy,xx),
 grid, MOD(LEN(SUBSTITUTE(BASE(sum,2),"0","")),2),
 BFSa(grid,1,1,31,39)
 )

Part 2

Description

Part 2 asks how many locations, including the start, I can reach in at most 50 steps. 

Solution

I put another BFS in the name manager. The function lists all the squares within 50 steps, and the answer is the number of rows:

=LAMBDA(grid,sx,sy,
 LET(
  w,COLUMNS(grid),
  h,ROWS(grid),
  dirs,{0,-1;-1,0;1,0;0,1},
  start,HSTACK(sx,sy,0),
  result,REDUCE(start,SEQUENCE(50),
   LAMBDA(state,lev,
    LET(
     keys,INDEX(state,,2)*1000+INDEX(state,,1),
     frontier,FILTER(state,INDEX(state,,3)=lev-1,HSTACK(-1,-1,-1)),
     IF(
      INDEX(frontier,1,1)=-1,
      state,
      LET(
       candidates,DROP(REDUCE(HSTACK(0,0,0),SEQUENCE(ROWS(frontier)),
        LAMBDA(acc,i,
         LET(
          x,INDEX(frontier,i,1),
          y,INDEX(frontier,i,2),
          nx,x+CHOOSECOLS(dirs,1),
          ny,y+CHOOSECOLS(dirs,2),
          VSTACK(acc,HSTACK(nx,ny,EXPAND(lev,4,1,lev)))
         )
        )
       ),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)=0,ISNA(XMATCH(k,keys)),XMATCH(k,cand_keys)=i)
         )
        )
        )
       ),
       fresh,FILTER(candidates,valid,HSTACK(-1,-1,-1)),
       IF(
        INDEX(fresh,1,1)=-1,
        state,
        VSTACK(state,fresh)
       )
      )
     )
    )
   )
  ),
  CHOOSECOLS(result,1,2)
  )
)

D2: =LET(
 input, A4,
 xx, SEQUENCE(,100,0),
 yy, SEQUENCE(100,,0),
 sum, LAMBDA(y,x, x*x + 3*x + 2*x*y + y + y*y+input)(yy,xx),
 grid, MOD(LEN(SUBSTITUTE(BASE(sum,2),"0","")),2),
 ROWS(BFSb(grid,1,1))
 )
Share:

Saturday, November 21, 2026

Advent of Code 2016 - Day 12: Leonardo's Monorail

Part 1

Description

The input is a small program for a computer with four registers, a, b, c and d, that all start at 0. There are four instructions:

  • cpy x y copies a number or a register x into register y.
  • inc x adds 1 to register x, and dec x subtracts 1.
  • jnz x y jumps y instructions forward or backward, but only if x is not zero (otherwise it just goes to the next instruction).

Part 1 asks what value register a holds when the program runs off the end.

Solution

I pasted the 23 instructions into A6:A28 and built the whole computer in one formula. Its state is a row of five numbers: a, b, c, d and step, which is the number of the next instruction (starting at 1). They are in C5:G5, with their names in C4:G4. The starting state is 0, 0, 0, 0, 1.

The formula repeats one instruction at a time with REDUCE. I allowed it up to a million of them, and once step is past the last instruction, the state no longer changes:

C6: =LET(
 aa, C5:G5,
 bb, $A$6:$A$28,
 cc, $C$4:$G$4,
 c, REDUCE(aa,SEQUENCE(1000000),
  LAMBDA(p,q,
   LET(
    step, INDEX(p,1,5),
    ins, TEXTSPLIT(INDEX($A$6:$A$28,INDEX(p,1,5),1)," "),
    ra, INDEX(ins,,2),
    rb, INDEX(ins,,3),
    stepconst, {0,0,0,0,1},
    vala, XLOOKUP(ra,cc,p,--ra),
    inst, SWITCH(INDEX(ins,,1),
     "cpy", IF(cc=rb,vala,p)+stepconst,
     "inc", IF(cc=ra,p+1,p)+stepconst,
     "dec", IF(cc=ra,p-1,p)+stepconst,
     "jnz", IF(vala<>0,stepconst*rb,stepconst)+p,),
    rs, IF(step>ROWS(bb),p, inst),
    rs)
   )),
c)
  • p is the state so far, and ins is the current instruction cut into its words.
  • ra and rb are the second and third words, the operands.
  • vala is the value of the first operand. If it is a register name, XLOOKUP finds that register in the state, and if not, it is a number and --ra converts the text to one.
  • For cpy, the register named rb is replaced by vala and the step goes up by one. inc and dec change the register named ra.
  • For jnz, if vala is not zero then rb is added to step, otherwise 1 is.

The formula fills C6:G6, and register a is the first number:

For the puzzle's example program the same formula leaves 42 in a.

Part 2

Description

The same program runs again, but register c now starts at 1. 

Solution

I put the new starting state, 0, 0, 1, 0, 1, in I5:M5. This version of the program runs for tens of millions of instructions, far more than one formula with a million steps can do. So I split the run into chunks. The same formula in I6 starts from I5:M5, I7 starts from I6:M6, and so on: each row carries the state on for another million instructions. After 28 rows the program has finished (step is 24, past the last instruction), and register a in the last row is the answer:

I6: =LET(aa,I5:M5, ... )          ← same formula as C6, starting from I5:M5
I7: =LET(aa,I6:M6, ... )          ← and so on down to I33
D2: =I33

This takes a long time to calculate. While working on the sheet it helps to switch Excel to manual calculation, or to paste the final values in place of the formulas.

Share:

Recent Posts

Categories

Blog Archive