Twelve Days · day 11 · both parts
Day 11: Reactor
Counting paths in a directed graph. Part 1 is small enough to walk; part 2 isn’t, and the interesting part is that the fix for it is one decorator and one bit of multiplication.
The puzzle, in my words
Each line names a device and the devices its outputs feed, like
bbb: ddd eee. Data only moves forwards, and there are no loops. Count the
different paths from the device you to the device out.
The example has ten lines, and five paths from you to out: through
bbb then ddd and ggg, or bbb then eee, or from ccc through
ddd/ggg, eee or fff.
Part 1: every path from you to out
Step 1: walk every path
Read the lines into a dictionary of lists, then walk from you with a
recursive depth-first search and count the times the walk reaches out.
out has no line of its own, hence graph.get(node, []):
def parse(text: str) -> dict[str, list[str]]:
graph = {}
for line in text.strip().splitlines():
name, outputs = line.split(":")
graph[name] = outputs.split()
return graph
def part1(text: str) -> int:
graph = parse(text)
def walk(node):
if node == "out":
return 1
total = 0
for nxt in graph.get(node, []):
total += walk(nxt)
return total
return walk("you")
There’s no visited set, and there doesn’t need to be one: with no loops the walk can’t come back to a device on its own path. It does go through the same device many times along different paths, though. The work grows with the number of paths, not with the size of the graph.
For part 1 that’s fine. On a generated input shaped like a puzzle input (600
devices in 30 layers, 1 to 6 outputs each, with you near the bottom) there
are only 50 paths from you, and the walk takes about 0.2 ms. Real inputs
seem to be similar: the one public solution I checked expects a part 1
answer of a few hundred in its tests.
Step 2: count each device once
The number of paths from ddd to out is the same whichever way the walk
arrived at ddd. So it only needs working out once: the count at a device is
the sum of the counts of the devices it feeds, and out counts 1.
functools.cache (Python 3.9+) remembers each result, so the recursion is
step 1’s and each device is worked out once:
from functools import cache
def count_paths(graph, start, end):
@cache
def paths(node):
if node == end:
return 1
return sum(paths(nxt) for nxt in graph.get(node, []))
return paths(start)
def part1(text: str) -> int:
return count_paths(parse(text), "you", "out")
paths is defined inside count_paths, so each call gets a new function
with an empty cache, tied to one graph and one end. That matters in part 2,
which calls it with different ends.
On the example, bbb is 1 + 1 = 2 (through ddd or eee), ccc is
1 + 1 + 1 = 3, and you is 2 + 3 = 5. On the generated input this is no
faster than step 1: 50 paths is too few for it to matter. Part 2 is where it
does.
Part 2: through both dac and fft
Now start at svr, and only count the paths to out that pass through both
dac and fft, in either order. Part 2 has its own example, with 14
devices: 8 paths from svr to out, of which 2 go through both.
Step 1: carry two flags
Step 1 of part 1 again, remembering whether the path has passed dac and
fft yet, and only counting it at out if it has seen both:
def part2(text: str) -> int:
graph = parse(text)
def walk(node, dac, fft):
dac = dac or node == "dac"
fft = fft or node == "fft"
if node == "out":
return 1 if dac and fft else 0
return sum(walk(nxt, dac, fft) for nxt in graph.get(node, []))
return walk("svr", False, False)
That’s right, and it gives 2 on the example, but it still visits every path
from svr, and there are a lot of them. The generated input has about
1.6 x 10^14 paths from svr to out. On a smaller generated graph this walk
managed about 2 million paths a second, which puts the full one at roughly
two and a half years.
Step 2: cache it, flags and all
Add @cache, as in part 1. The only catch is that the count from a device now
depends on what the path has already seen. In the example, a path reaches
ccc either through fft (via aaa) or not (via tty); from ccc both of
its paths through dac count in the first case and none do in the second. So
the flags are arguments of the cached function, and each device has up to four
entries:
from functools import cache
def part2(text: str) -> int:
graph = parse(text)
@cache
def paths(node, dac, fft):
dac = dac or node == "dac"
fft = fft or node == "fft"
if node == "out":
return 1 if dac and fft else 0
return sum(paths(nxt, dac, fft) for nxt in graph.get(node, []))
return paths("svr", False, False)
On the generated input that’s under a millisecond, for an answer of about 2 x 10^11. Python’s integers don’t overflow, so counts this size need no special care.
Step 3: multiply the legs
There’s a way without flags. A path through both waypoints either goes svr
to dac to fft to out, or svr to fft to dac to out. It can’t do
both: that would need a way back from the second waypoint to the first, which
is a loop. And within one order, any way into a waypoint can be followed by
any way out of it, so the count is a product of three legs, each counted with
part 1’s count_paths. itertools.pairwise (Python 3.10+) gives the legs
as pairs of neighbouring stops, and math.prod multiplies them:
from itertools import pairwise
from math import prod
def part2(text: str) -> int:
graph = parse(text)
def via(*stops):
return prod(count_paths(graph, a, b) for a, b in pairwise(stops))
return via("svr", "dac", "fft", "out") + via("svr", "fft", "dac", "out")
On the example, svr to dac is 2 and fft to out is 4, but there’s no
way from dac to fft, so the first order gives 2 x 0 x 4 = 0. The second
gives 1 x 1 x 2 = 2: one way from svr to fft, one from fft to dac, two
from dac to out.
This isn’t faster than step 2 (about 1 ms on the generated input, as it makes
six passes instead of one). What I like about it is that it needs nothing
new: part 1’s function, called six times. The legs a path can’t take, like
dac to fft here, just come out as 0.
All of this was checked on the puzzle’s examples and on generated inputs, not on a puzzle input of my own.