Twelve Days · day 2 · both parts
Day 2: Fulminating Farmland
A short one: part 1 is a few lines of modular arithmetic. Part 2 asks for a simulation, and the interesting part is noticing you don’t need to run it.
The puzzle, in my words
Waypoints repeat around a track in six colours, roygbv (red, orange,
yellow, green, blue, violet), and a robot starts on a red one. Each letter of
its program sends it forward to the next waypoint of that colour. That’s 1 to
5 steps, or a full lap of 6 if it’s the colour the robot is already on. Add up
the distances.
In the example program obbvb, the robot moves 1 (red to orange), 3 (to
blue), 6 (blue again, a full lap), 1 (to violet) and 5 (back round to blue):
16 in total.
Part 1: how far the program goes
The animation runs a longer example, groovyyoyo, in its own order: a
distance of 37 in all.
groovyyoyo. Right: the program, each move’s distance, and the letters not used yet, stacked by colour.Step 1: the first version
Give each colour its position in roygbv. A move is the difference between
the two positions, wrapped around the ring with %, and a difference of 0
means a full lap.
def part1(text: str) -> int:
st = "roygbv"
ans = 0
p = 0
pos = {ch: idx for idx, ch in enumerate(st)}
for ch in text.strip():
next_p = pos[ch]
d = (next_p - p + len(st)) % len(st)
ans += d if d > 0 else len(st)
p = next_p
return ans
Step 2: Python’s % is already non-negative
The + len(st) is there to keep the difference from going negative, which
it would in C or Java, where -2 % 6 is -2. In Python the result of %
takes the sign of the divisor, so -2 % 6 is 4 and the extra term does
nothing. And since 0 is falsy, x or 6 turns a 0 into a full lap:
def part1(text: str) -> int:
pos = {ch: i for i, ch in enumerate("roygbv")}
total, p = 0, 0
for ch in text.strip():
total += (pos[ch] - p) % 6 or 6
p = pos[ch]
return total
Step 3: moves are pairs of letters
Each move only depends on where the robot is and where it goes next, so it’s
a function of two neighbouring letters. Put the starting r in front of the
program, and itertools.pairwise (Python 3.10+) yields every (from, to)
pair. The loop becomes a sum:
from itertools import pairwise
def part1(text: str) -> int:
pos = {ch: i for i, ch in enumerate("roygbv")}
return sum((pos[b] - pos[a]) % 6 or 6 for a, b in pairwise("r" + text.strip()))
Part 2: the longest way round
Now the program can be reordered, and the rule is greedy: before every move,
use the letter that sends the robot farthest. That’s the colour it stands on
if any are left (6 steps), otherwise the colour just behind it (5), and so
on. Rearranging rybryb this way gives rrbbyy, for 6 + 6 + 4 + 6 + 4 + 6 =
32.
Step 1: simulate it
Count the letters, then at each move walk backwards round the ring from the current colour and take the first one that’s still left:
from collections import Counter
def part2(text: str) -> int:
colors = "roygbv"
prog = text.strip()
pos = {ch: i for i, ch in enumerate(colors)}
left = Counter(prog)
total, p = 0, 0
for _ in range(len(prog)):
for back in range(6):
ch = colors[(p - back) % 6]
if left[ch]:
break
left[ch] -= 1
total += (pos[ch] - p) % 6 or 6
p = pos[ch]
return total
That’s at most six checks per letter, and the input is under a thousand letters. It’s fast enough, and it’s the answer I submitted.
Step 2: look at what the simulation does
Watch the robot move and a pattern shows up. It stays on its colour until that colour runs out, because a full lap is always the best move. Then it steps back to the nearest colour behind it that is left, and stays there. So it visits the colours in the order r, v, b, g, y, o, each exactly once, skipping any the program doesn’t have.
That means every letter costs a full lap of 6, except the first letter of each colour, which costs the hop from the previous colour. Only the counts matter:
from collections import Counter
def part2(text: str) -> int:
counts = Counter(text.strip())
total, p = 0, 0
for i in (0, 5, 4, 3, 2, 1): # r, v, b, g, y, o
n = counts["roygbv"[i]]
if n:
total += ((i - p) % 6 or 6) + 6 * (n - 1)
p = i
return total
Check it on rybryb: two reds at 6 each, then blue (no violet, so a hop of
4) and one more lap, then yellow (no green, another hop of 4) and one lap.
That’s 12 + 10 + 10 = 32.
The loop now runs six times whatever the program’s length. For an input this size the speed doesn’t matter; the point is that step 2 explains the answer. It could also be wrong in a way the simulation can’t be, so the tests run both versions on 500 random programs, including ones that skip colours, and check they agree.