@xavdid does Advent of Code

Fulminating Farmland

Published: 2026-12-02Original Puzzle

Part 1

Today’s puzzle has us walking down an infinite track, calculating the distance needed to reach each next step.

My initial approach involved using itertools.cycle (docs) to let me loop over the sequence indefinitely. But, figuring out where to stop meant advancing the iterator until we found our target, which felt a little clunky.

Instead, I wanted code that could easily answer the question “what is the current distance to every letter?”. Because there are only 6 letters and the distance between them is always the same, we could pre-compute every possible distance:

distances = {
"r": {
"o": 1,
"y": 2,
"g": 3,
# ...
},
"o": {
"y": 1,
"g": 2,
"b": 3,
# ...
},
# ...
}

But we don’t want to write that by hand! So we’ll build it dynamically. For each instruction, we want to store the distance of each other instruction. For the initial position, we can walk along the string roygbv:

distances = {}
steps = enumerate("roygbv")
_, start = next(steps) # (0, 'r')
distances[start] = {letter: distance for distance, letter in steps}
distances[start][start] = len(instructions)
# => {'r': {'o': 1, 'y': 2, 'g': 3, 'b': 4, 'v': 5, 'r': 6}}

We’re using a dict comprehension here to turn our enumerated string into keys and values: the index of each letter in the string. We also add start (set to 'r') into the map manually, since its index of 0 would be incorrect.

And this would work if we never move! But we do. So we need a way to “rotate” the string, so we can build the same dict with the string oygbvr. Enter Python’s deque (double-ended queue) class, which has the very useful .rotate() method:

from collections import deque
d = deque('roygbv')
# => deque(['r', 'o', 'y', 'g', 'b', 'v'])
d.rotate(-1)
# => deque(['o', 'y', 'g', 'b', 'v', 'r'])

.rotate() without arguments hifts elements to the right, but we want to step to the left for this example, hence the -1

A deque keeps its relative order even when it rotates, which is perfect! We can “walk” the instructions and add each to the distances dict:

instructions = deque("roygbv")
distances = {}
for _ in range(len(instructions)):
steps = enumerate("roygbv")
steps = enumerate(instructions)
_, start = next(steps)
distances[start] = {letter: distance for distance, letter in steps}
distances[start][start] = len(instructions)
instructions.rotate()

We can use .rotate() without an argument here, since the order we add letters to distances doesn’t matter as long as each sub-dict is correct.

From there, our actual answer is simple:

class Solution(TextSolution):
def part_1(self) -> int:
distances = {}
... # build map
total = 0
current = "r" # starting position
for target in self.input:
total += distances[current][target]
current = target
return total

Part 2

Now insteaed of walking the input in order, we take the best available move. This requires two new bits of code:

The fisrt one is simple. We can use the same container we did yesterday, Counter. In addition to surfacing the most common items, it will also let us check (and modify!) the value for any key.

The second takes a little more work. Let’s start with a broken implementation using our distances map from part 1. The approach is similar:

from collections import Counter, deque
available_steps = Counter(self.input)
class Solution(TextSolution):
...
def part_2(self) -> int:
distances = { ... } # see above
available_steps = Counter(self.input)
total = 0
current = "r"
for _ in self.input:
for target, distance in distances[current].items():
if available_steps[target]:
available_steps[target] -= 1
total += distance
current = target
break
return total

Our logic is in a loop that ensures we only step as many times as there are possible moves.

Inside that loop, we check each possible move until we find one that’s still available. Once found, we remove it from the remaining available_steps, add its distance to our total, and finish our move by updating current, similar to before.

But! This code doesn’t quite work. Iterating over distances[current].items() seems to be consistently finding the shortest distance it could travel, so our answer is way under.

It all boils down to the way we built distances. A reminder:

...
distances[start] = {letter: distance for distance, letter in steps}

Elements are added in ascending index order, meaning the shortest distances are always inserted first. And, since Python 3.7, dictionaries remember their insertion order when iterating! So we have two options:

  1. Sort distances[current].items() on every step
  2. Build distances more carefully so that the biggest value is first

The first one works, but feels wasteful. We’re sorting the same data the same way every time. Instead, we sould set up the data the right way in the first place. And, if we do that right, we can reuse it for both parts (since the resulting dicts will be equal, just constructed slightly differently). So!

Our approach is similar, but we’ll have to do a little index math and a little reversing. Let’s see it in action:

def build_distance_map():
instructions = deque("roygbv")
num_instructions = len(instructions)
distances = {}
for _ in range(num_instructions):
start, *rest = instructions # 'r', ['o', 'y', ...]
res = {start: num_instructions}
for idx, c in enumerate(reversed(rest)):
res[c] = num_instructions - 1 - idx
distances[start] = res
instructions.rotate()
return distances

A little destructuring gets us our starting letter and the other ones, separated nicely. We reverse the rest (since they have to go in farthest first) and do a little arithmetic to make sure they have the right value (the full length of the original array, minus the item we already removed, minus the distance we’ve traveled).

We can use that new function for both parts and suddenly, part 2 just works!