Twenty-Five Days · day 21 · both parts
Day 21: Keypad Conundrum
The sequences in this one grow about two and a half times with every robot you add, so part 2 can’t build them. The way out is noticing that the robots keep going back to the same key, which means a move costs the same wherever it happens.
The puzzle, in my words
A robot has to type a code like 029A on a door’s numeric keypad (789,
456, 123, then a gap and 0A). It can’t be told what to press: its arm is
steered from a directional keypad with an up key and A on top (a gap on
the left) and left, down, right underneath. Each arrow moves the arm one key;
A makes the robot press whatever the arm points at. That directional keypad
is pressed by another robot, steered the same way from another directional
keypad, and so on, until a keypad you press yourself. Every arm starts on A,
and no arm may ever point at a gap.
A code’s complexity is the length of the shortest sequence you can press,
times the number in the code. In part 1 there are two robot-operated
directional keypads between you and the door robot. The example’s codes
029A, 980A, 179A, 456A and 379A need 68, 60, 68, 64 and 64 presses,
and 68 × 29 + 60 × 980 + 68 × 179 + 64 × 456 + 64 × 379 = 126384.
Part 1: two robots in the middle
Step 1: search the whole chain
The safe first version doesn’t try to be clever about paths. The state is
where every arm points plus how many characters of the code are typed. One
press of yours is one step: an arrow moves the next arm, and A makes that
robot press the key under its arm, which is passed on to the next robot in
the same way, until it either moves an arm or reaches the door. A breadth-first
search finds the fewest presses that type the whole code:
from collections import deque
NUMERIC = ("789", "456", "123", " 0A")
DIRECTIONAL = (" ^A", "<v>")
MOVES = {"^": (-1, 0), "v": (1, 0), "<": (0, -1), ">": (0, 1)}
def find(pad, key):
for r, row in enumerate(pad):
if key in row:
return r, row.index(key)
def presses_by_search(code, robots):
pads = [NUMERIC] + [DIRECTIONAL] * robots # pads[0] is the door
start = (tuple(find(pad, "A") for pad in pads), 0)
dist = {start: 0}
queue = deque([start])
while queue:
state = queue.popleft()
arms, typed = state
if typed == len(code):
return dist[state]
for key in "^v<>A":
new_arms = list(arms)
new_typed = typed
ok = True
level = robots
while True:
pad = pads[level]
r, c = new_arms[level]
if key in MOVES:
dr, dc = MOVES[key]
r, c = r + dr, c + dc
if 0 <= r < len(pad) and 0 <= c < 3 and pad[r][c] != " ":
new_arms[level] = (r, c)
else:
ok = False # off the keypad, or over the gap
break
key = pad[r][c] # this robot presses the key it points at
if level == 0: # ... and that was the door
if key == code[typed]:
new_typed = typed + 1
else:
ok = False
break
level -= 1
nxt = (tuple(new_arms), new_typed)
if ok and nxt not in dist:
dist[nxt] = dist[state] + 1
queue.append(nxt)
def part1(text: str) -> int:
return sum(presses_by_search(code, 2) * int(code[:-1]) for code in text.split())
With two robots there are only 11 × 5 × 5 arm positions, so this is quick (about 7 ms for five generated codes). It makes no assumption about what a good sequence looks like, which is why the tests use it to check everything that follows. But each robot added multiplies the states by 5.
Step 2: one move at a time
Watch the clip at the moment the door gets a key: every arm above it points
at A. That isn’t luck. For a robot to press anything, the robot steering it
must have pressed A, and so on all the way up to you. So between two presses
at any level, everything closer to you is back on A, and the cost of a
sequence is just the sum of the costs of its moves, each one taken on its own.
A move from one key to another needs some arrows and an A. Only two orders
are worth trying: all the horizontal steps then all the vertical ones, or the
other way round. Zigzagging only makes the robot one level up change
direction more often, and each change costs extra presses there. One of the
two orders may turn its corner on the gap, and then it’s out:
from itertools import pairwise
def paths(pad, a, b):
(r1, c1), (r2, c2) = find(pad, a), find(pad, b)
h = ("<" if c2 < c1 else ">") * abs(c2 - c1)
v = ("^" if r2 < r1 else "v") * abs(r2 - r1)
result = set()
if pad[r1][c2] != " ": # horizontal first turns at (from-row, to-column)
result.add(h + v + "A")
if pad[r2][c1] != " ": # vertical first turns at (to-row, from-column)
result.add(v + h + "A")
return result
def typing_cost(seq, depth):
"""Your presses to get seq pressed on a directional keypad depth robots away."""
if depth == 0:
return len(seq) # it's your own keypad
return sum(
min(typing_cost(p, depth - 1) for p in paths(DIRECTIONAL, a, b))
for a, b in pairwise("A" + seq)
)
def part1(text: str) -> int:
total = 0
for code in text.split():
presses = sum(
min(typing_cost(p, 2) for p in paths(NUMERIC, a, b))
for a, b in pairwise("A" + code)
)
total += presses * int(code[:-1])
return total
pairwise("A" + seq) (Python 3.10+) gives the moves, starting from the A
the arm is on. A straight move has the same string both ways, which is why
paths returns a set.
The claim that two orders are enough is the one thing here that isn’t obvious, so it’s tested rather than trusted: this step agrees with the search on random codes with up to 3 robots in between (and part 2’s table version agrees with it at 4), and a version that tries every shortest interleaving of the steps gets the same answers with 2, 5 and 25 robots. On the five generated codes this takes about 0.4 ms.
Part 2: twenty-five robots
Part 2 puts 25 robot-operated directional keypads between you and the door
instead of 2. Write-ups say the page gives no example answer for it, and
report 154115708116294 for the five example codes; the code here gets that
too.
For 029A alone that’s 82050061710 presses.
Step 1: remember each move
Step 2’s recursion gets about 3.3 times slower with each robot added (0.4 ms
with 2, 750 ms with 8, on the generated codes), so 25 is out of reach. But
look at what it computes: the cost of a move depends only on the two keys and
the depth. There are 5 × 5 moves on a directional keypad and 26 depths, so at
most 650 different answers, each recomputed many times. functools.cache
(Python 3.9+) keeps each one after the first time:
from functools import cache
@cache
def move_cost(a, b, depth):
"""Your presses to move an arm depth robots away from a to b and press b."""
if depth == 0:
return 1 # your own finger
return min(
sum(move_cost(x, y, depth - 1) for x, y in pairwise("A" + p))
for p in paths(DIRECTIONAL, a, b)
)
def part2(text: str) -> int:
total = 0
for code in text.split():
presses = sum(
min(sum(move_cost(x, y, 25) for x, y in pairwise("A" + p)) for p in paths(NUMERIC, a, b))
for a, b in pairwise("A" + code)
)
total += presses * int(code[:-1])
return total
It’s the same recursion, asked about one move at a time. Step 2’s version
would also be fine with a cache: it only ever passes short paths of a few
keys down a level, so its calls repeat just as much (putting @cache on
typing_cost gives the same answer from 388 distinct calls). Keying on
(from, to, depth) is still the clearer choice, because it says exactly what
is being remembered: a 5 × 5 table per depth, which the next step builds
directly. The sequences themselves are never built, which is just as well at
82 billion presses. About 0.7 ms on the generated codes, with the cache
emptied before each run.
Step 2: fill in the table level by level
The cache is a table that fills itself in on demand. It can be filled in directly instead, one depth at a time: start with all ones at depth 0, and build each depth’s 25 entries from the one below. That’s what the clip shows.
def cheapest(pad, a, b, table):
return min(sum(table[m] for m in pairwise("A" + p)) for p in paths(pad, a, b))
def part2(text: str) -> int:
keys = "^A<v>"
table = {(a, b): 1 for a in keys for b in keys}
for _ in range(25):
table = {(a, b): cheapest(DIRECTIONAL, a, b, table) for a in keys for b in keys}
total = 0
for code in text.split():
presses = sum(cheapest(NUMERIC, a, b, table) for a, b in pairwise("A" + code))
total += presses * int(code[:-1])
return total
No recursion, and the whole state is 25 numbers. It’s no faster than the
cache (about 0.8 ms, as it works out every entry whether it’s needed or not),
but the growth is easy to watch: 029A needs 12, 28, 68, 164, 404, 998, …
presses as the depth goes from 0 up, and from about depth 6 on each level is
about 2.49 times the one before.
Setting the depth to 2 gives part 1’s answer again, and the tests check both part 2 steps against the search at small depths.
The timings are best-of-three on a busy machine, so take them as rough. All of this was checked on the puzzle’s examples and on generated inputs, not on a puzzle input of my own.