Twenty-Five Days · day 20 · both parts
Day 20: Race Condition
A grid day where the grid stops mattering quickly. Once every track cell has its time in the race written on it, a cheat is a subtraction. Part 2 only makes the jump longer, and the interesting part is how few pairs of cells you actually need to look at.
The puzzle, in my words
The map is a racetrack: track cells and walls, a start S and an end E.
There is exactly one way through, a corridor with no branches, and each move
to a neighbouring cell takes one picosecond. In the 15x15 example the race
takes 84.
Once per race a program may cheat: for up to 2 moves it can go through walls, as long as it finishes on track. A cheat is identified only by where it starts and where it ends. How many cheats save at least 100 picoseconds?
The example has no cheat that good, so the page lists all of them instead, by time saved: 14 save 2, 14 save 4, 2 save 6, 4 save 8, 2 save 10, 3 save 12, and one each saves 20, 36, 38, 40 and 64. That’s 44 cheats, and the tests check every step against that whole list.
Part 1: two moves through a wall
Step 1: the first version
First, the time at which the race reaches each track cell: a breadth-first
search from S. Then from every track cell, play the cheat out: two moves in
any direction, walls or not, and keep it if it lands on track. A cheat from
a reaches b at time dist[a] + 2 instead of dist[b], so it saves
dist[b] - dist[a] - 2.
Two different pairs of moves can reach the same cell (up then right, right
then up), and the puzzle counts a cheat by its start and end, so the cheats
go into a dict keyed by (start, end):
from collections import deque
def grid(text: str):
track = set()
for r, line in enumerate(text.split()):
for c, ch in enumerate(line):
if ch != "#":
track.add((r, c))
if ch == "S":
start = (r, c)
elif ch == "E":
end = (r, c)
return track, start, end
def part1(text: str, min_save: int = 100) -> int:
track, start, _ = grid(text)
dist = {start: 0}
queue = deque([start])
while queue:
r, c = queue.popleft()
for dr, dc in ((0, 1), (0, -1), (1, 0), (-1, 0)):
n = (r + dr, c + dc)
if n in track and n not in dist:
dist[n] = dist[(r, c)] + 1
queue.append(n)
cheats = {}
for r, c in track:
for dr1, dc1 in ((0, 1), (0, -1), (1, 0), (-1, 0)):
for dr2, dc2 in ((0, 1), (0, -1), (1, 0), (-1, 0)):
end = (r + dr1 + dr2, c + dc1 + dc2)
if end in track:
cheats[(r, c), end] = dist[end] - dist[(r, c)] - 2
return sum(saved >= min_save for saved in cheats.values())
min_save is a parameter so the tests can ask for the example’s thresholds;
the puzzle’s own question is the default, 100. Summing the comparisons
counts them, since True is 1.
Step 2: name the landing cells
Two moves can only land back where they started or on the 8 cells at
Manhattan distance exactly 2: four straight across a wall, four diagonally
round a corner. Listing those
directly removes the dict, because each (start, end) pair now comes up
once.
The track also has no branches (the puzzle says so; on the example the
walk covers every track cell, which the tests check, and the same is
reported for real inputs, which I couldn’t check), so the BFS isn’t
needed: walking the
corridor from S, always to the neighbour we didn’t just come from, visits
the cells in race order, and a cell’s time is its index in that list.
Positions are complex numbers, column + row·i, so a neighbour or a landing
cell is one addition:
def race(text: str) -> list[complex]:
cells, start, end = grid(text)
track = {complex(c, r) for r, c in cells}
here, goal = complex(start[1], start[0]), complex(end[1], end[0])
path = [here]
while here != goal:
back = path[-2] if len(path) > 1 else None
here = next(n for n in (here + 1, here - 1, here + 1j, here - 1j)
if n in track and n != back)
path.append(here)
return path
JUMP_2 = [complex(dx, dy) for dx in range(-2, 3) for dy in range(-2, 3)
if abs(dx) + abs(dy) == 2]
def part1(text: str, min_save: int = 100) -> int:
path = race(text)
time = {p: t for t, p in enumerate(path)}
return sum(time.get(p + d, -1) - t - 2 >= min_save
for t, p in enumerate(path) for d in JUMP_2)
A landing cell that’s a wall isn’t in time, and .get returns -1, which
makes the saving negative so it is never counted.
The diagonal cases are easy to leave out: every cheat drawn on the puzzle page goes straight across a wall, and the example has no diagonal cheat that saves time, so a straight-only version passes the example. A track can still have one: two cells touching only at a corner, with walls on both sides of it. The tests include a small map where the best cheat is like that (the only one that saves 10), and random tracks whose corners can touch. I don’t know whether real inputs have any; I couldn’t check.
On a generated 141x141 map (the size reported for real inputs) with a track of about 9,800 cells, step 1 took about 50 ms and step 2 about 14 ms. The machine was busy with other work, so those are rough.
Part 2: up to 20 moves
Now a cheat may last up to 20 moves. It is still known only by its start and
end, so the route between them doesn’t matter and costs the Manhattan
distance: the saving of a jump from a to b is time[b] - time[a] - distance(a, b), for any two track cells at most 20 apart. Part 1 is the
case of 2.
On the example, the cheats that save at least 50 are: 32 that save 50, 31 that save 52, and so on down to 3 that save 76. That’s 285. Part 2 isn’t on the page I worked from; these numbers are from public solutions’ tests, and a direct version of the rule reproduces them.
Step 1: every pair
With the track in race order, the rule reads straight off: for every pair of
track cells, the earlier one i and the later one j, check the distance
and the saving.
def part2(text: str, min_save: int = 100, max_cheat: int = 20) -> int:
path = race(text)
count = 0
for i, a in enumerate(path):
for j in range(i + 1, len(path)):
b = path[j]
d = int(abs(a.real - b.real) + abs(a.imag - b.imag))
if d <= max_cheat and j - i - d >= min_save:
count += 1
return count
That’s about n²/2 pairs: 48 million for a track of 9,800 cells, and 7.2 seconds on the generated map.
Step 2: look around each cell
Most of those pairs are far apart. The cells within 20 moves of a cell form a diamond of 840 offsets (2·20·21, not counting the cell itself), the same for every cell, so build them once and look each one up, as in part 1:
def diamond(radius: int) -> list[tuple[complex, int]]:
return [(complex(dx, dy), abs(dx) + abs(dy))
for dx in range(-radius, radius + 1)
for dy in range(-radius, radius + 1)
if 2 <= abs(dx) + abs(dy) <= radius]
def part2(text: str, min_save: int = 100, max_cheat: int = 20) -> int:
path = race(text)
time = {p: t for t, p in enumerate(path)}
offsets = diamond(max_cheat)
return sum(time.get(p + off, -1) - t - d >= min_save
for t, p in enumerate(path) for off, d in offsets)
8 million lookups instead of 48 million pairs: 0.8 seconds on the same map. (Offsets at distance 1 are left out; they are the neighbours on the track and never save anything.)
Step 3: skip along the track
Back to pairs in race order, but with two observations that skip most of them.
First, a cheat from i that lands at j saves j - i - d, and d is at
least 2, so nothing before j = i + min_save + 2 can save enough. With the
real threshold of 100 that skips the first hundred cells after every start.
Second, each step along the track moves one cell, which changes the
Manhattan distance to a fixed cell by exactly 1. So if cell j is d moves
away from i and d is more than 20, the next d - 21 cells are all still
out of reach, and j can jump ahead by d - 20:
def part2(text: str, min_save: int = 100, max_cheat: int = 20) -> int:
path = race(text)
xs = [int(p.real) for p in path]
ys = [int(p.imag) for p in path]
n = len(path)
count = 0
for i in range(n):
x, y = xs[i], ys[i]
j = i + min_save + 2
while j < n:
d = abs(xs[j] - x) + abs(ys[j] - y)
if d > max_cheat:
j += d - max_cheat
else:
count += j - i - d >= min_save
j += 1
return count
On the generated map this took 0.22 seconds, against 0.8 for the diamond. How much it skips depends on the track’s shape: the further the corridor wanders from a start, the bigger each leap.
The generated map is a stand-in: a random corridor through every cell of a 141x141 grid’s odd rows and columns, with one-cell walls between all of its turns, so it has many more shortcuts than a real input would (over a million part 2 cheats at 100). The timings are for comparing the steps with each other, on a loaded machine, not a prediction for a real input.
All three steps take max_cheat, and with max_cheat=2 the tests check
they give part 1’s list. Every step of both parts is also checked against a
version written straight from the rules (a search from S, a search from
E, every pair of track cells within reach, which doesn’t assume the track
has no branches) on 150 random tracks.
All of this was checked on the puzzle’s examples and on generated inputs, not on a puzzle input of my own.