Skip to content
advent of code 2017

day 03

spiral memory

approach

part 1 never builds the spiral. spiral_coord walks it in straight runs: move step cells in the current direction, turn left by rotating (dr, dc), and grow step by one after every second turn. it jumps whole runs at once until the index is used up, then returns the manhattan distance of the final coordinate.

part 2 does build it: a generator walks the spiral one cell at a time, writes the sum of the already-filled neighbours (all eight around it) into a dict, and yields each value. the answer is the first value larger than the input.

the trick

spiral run lengths go 1, 1, 2, 2, 3, 3, …, so a counter that bumps every other turn is all the bookkeeping needed.

python
while index:
    s = min(index, step)
    rs, cs = dr * s, dc * s
    r, c = r + rs, c + cs
    index -= s
    dr, dc = -dc, dr

    if i & 1 == 1:
        step += 1
    i += 1