Twelve Days · day 7 · both parts
Day 7: Laboratories
A grid puzzle that is really a counting puzzle. Part 1 is a simulation where merging beams is the only catch. Part 2 asks for a number far too large to reach by walking paths, and the fix is to count the paths as they merge.
The puzzle, in my words
A beam enters a diagram at S and falls straight down. When it reaches a
splitter ^, it stops, and two new beams fall from the cells just left and
just right of the splitter. Beams that land in the same column are one beam.
Count how many times the beam is split.
The example is a triangle of 22 splitters in 16 rows. The beam is split 21 times: one splitter, in the bottom row, sits between two beams and no beam ever reaches it.
Part 1: counting the splits
Step 1: draw the beams
The puzzle explains itself with pictures in which every beam cell is a |.
Doing exactly that is a fine first version: copy the grid, go down it row by
row, and continue every beam that has an S or a | above it.
def part1(text: str) -> int:
grid = [list(line) for line in text.split()]
splits = 0
for r in range(1, len(grid)):
for c in range(len(grid[r])):
if grid[r - 1][c] not in "S|":
continue
if grid[r][c] == "^":
splits += 1
for side in (c - 1, c + 1):
if grid[r][side] == ".":
grid[r][side] = "|"
else:
grid[r][c] = "|"
return splits
Merging takes no code at all: two splitters that send a beam into the same
cell both write the same |, and the row below sees one beam. One thing this
relies on is that no splitter sits at the edge. In Python grid[r][-1] is the
last cell of the row, not an error, so a splitter in column 0 would quietly
send a beam to the far side. Real inputs are reported to have no splitters at
the edges and no two side by side; I couldn’t check that here.
Step 2: a set of columns
Only the columns that carry a beam matter, so keep those in a set. Each row, the splitters that get hit are the intersection of the beams with the row’s splitters; those beams are replaced by their two neighbours, and a set union does the merging.
def part1(text: str) -> int:
lines = text.split()
beams = {lines[0].index("S")}
splits = 0
for line in lines[1:]:
hit = beams & {c for c, ch in enumerate(line) if ch == "^"}
splits += len(hit)
beams = (beams - hit) | {c + d for c in hit for d in (-1, 1)}
return splits
This isn’t about speed: on a generated diagram of 142 rows by 141 columns (a size I chose: real inputs are reported to be a triangle like the example’s, much larger, but I couldn’t find their exact size), step 1 takes 1.8 ms and step 2 1.1 ms. The point is that the set is the state part 2 builds on.
Part 2: counting timelines
Now a single particle goes through, and at every splitter it goes both ways:
time splits into a timeline where it went left and one where it went right.
Count the timelines, which is the number of different paths from S out of
the bottom. Merging no longer saves anything, since two paths that meet are
still two paths. The example has 40.
Step 1: follow every timeline
The rule translates directly into a recursion. From a cell, the number of timelines is 1 once the particle is past the bottom row, the sum of both sides on a splitter, and whatever the cell below gives otherwise.
def part2(text: str) -> int:
lines = text.split()
def timelines(r: int, c: int) -> int:
if r == len(lines):
return 1
if lines[r][c] == "^":
return timelines(r + 1, c - 1) + timelines(r + 1, c + 1)
return timelines(r + 1, c)
return timelines(1, lines[0].index("S"))
This gives 40 on the example, and it is the version that checks the others, because it really does follow each path. That is also its problem: it takes time in proportion to the answer. On generated diagrams it takes 0.17 ms with 10 rows of splitters, 13.5 ms with 18, and 57 ms with 20 (82,634 timelines), about 0.7 µs per timeline. The full-size generated diagram has about 9.2 × 10¹⁵ timelines, so at that rate it would take at least two centuries (the cost per timeline grows a little with depth). That’s an extrapolation; I didn’t run it. One solver reports a real answer past 10¹⁵ as well.
Step 2: remember each cell
timelines(r, c) depends only on r and c, and the same cell is reached by
a huge number of paths. functools.cache (Python 3.9+) stores the result for
each argument pair, so each cell is worked out once: at most rows × columns
of them, instead of one call per timeline:
from functools import cache
def part2(text: str) -> int:
lines = text.split()
@cache
def timelines(r: int, c: int) -> int:
if r == len(lines):
return 1
if lines[r][c] == "^":
return timelines(r + 1, c - 1) + timelines(r + 1, c + 1)
return timelines(r + 1, c)
return timelines(1, lines[0].index("S"))
Defining timelines inside part2 means every call of part2 gets a fresh
cache, so one diagram’s answers never leak into the next. The recursion is
only as deep as the diagram is tall, about 140 calls, well under Python’s
default limit of 1000. This takes 1.8 ms on the generated diagram, and the
answer, about 9 × 10¹⁵, is no trouble either: Python’s integers don’t overflow.
Step 3: a Counter per row
The recursion starts at the top but gets its numbers from the bottom up. The
same sums can be done top-down instead, as a direct extension of part 1: instead of a set of
columns, keep a Counter of how many timelines are in each column. A splitter
hands its count to both neighbours; columns that meet add up.
from collections import Counter
def part2(text: str) -> int:
lines = text.split()
counts = Counter({lines[0].index("S"): 1})
for line in lines[1:]:
below = Counter()
for c, n in counts.items():
if line[c] == "^":
below[c - 1] += n
below[c + 1] += n
else:
below[c] += n
counts = below
return counts.total()
A Counter gives 0 for a missing key, so below[c - 1] += n needs no check,
and Counter.total() (Python 3.10+) is the sum of the counts. On the example
the first rows are 1, then 1 1, then 1 2 1, then 1 3 3 1: Pascal’s triangle,
as long as every splitter is there. The first gap breaks the pattern (the
row after is 1 4 3 3 1 1): a timeline that falls through a gap doesn’t split,
which is why the bottom row adds up to 40 and not 2⁷ = 128. This takes 1.5 ms on the generated diagram, and the same loop
answers part 1 too if it also counts the splitters with a nonzero count above
them. The tests check that, and run all three part 2 steps (and both part 1
steps) on 300 random diagrams to check they agree.
All of this was checked on the puzzle’s example and on generated inputs, not on a puzzle input of my own.