← blog

Twenty-Five Days · day 6 · both parts

Day 6: Guard Gallivant

the puzzle ↗ #aoc-2024#python

Part 1 is a short simulation, and a good excuse for complex numbers on a grid. Part 2 is a brute force that is too slow if written the obvious way, and the interesting part is how much of the work it can skip.

The puzzle, in my words

A map of a lab: # cells are obstacles, and a guard stands on ^, facing up. She walks straight ahead, and whenever the cell in front of her is an obstacle she turns right instead, until she walks off the map. Count the cells she stands on, the start included.

On the example’s 10 by 10 map she makes ten turns before she leaves at the bottom, and stands on 41 different cells.

Part 1: follow the guard

Part 1 on the example. Right: the number of cells visited so far and the turns made.

Step 1: the first version

Keep the map as rows of text, and the guard’s heading as an index into a list of steps in turning order (up, right, down, left), so a right turn is the next one in the list:

DIRS = [(-1, 0), (0, 1), (1, 0), (0, -1)]


def part1(text: str) -> int:
    rows = text.split()
    height, width = len(rows), len(rows[0])
    for r, row in enumerate(rows):
        if "^" in row:
            r0, c0 = r, row.index("^")
    r, c, d = r0, c0, 0
    visited = {(r, c)}
    while True:
        nr, nc = r + DIRS[d][0], c + DIRS[d][1]
        if not (0 <= nr < height and 0 <= nc < width):
            return len(visited)
        if rows[nr][nc] == "#":
            d = (d + 1) % 4
        else:
            r, c = nr, nc
            visited.add((r, c))

The set does the “distinct” part: the path crosses itself, and a cell she stands on twice is added twice but counted once.

Step 2: complex numbers

A position can be one complex number, x + y*1j, and a heading is one step: -1j is up, since y grows downwards like the row numbers. Moving is then pos + d, and a right turn is a multiplication by 1j: up times 1j is 1 (right), right times 1j is 1j (down), and so on round. On axes with y growing upwards, as in maths, the same turn would be * -1j, so the sign depends on which way y points.

Storing the map as a dict from position to character also removes the bounds check: grid.get(pos + d) is None off the map. The walk becomes a generator that yields the guard’s state at each beat, which part 2 will reuse:

def parse(text: str) -> tuple[dict[complex, str], complex]:
    grid = {complex(x, y): ch for y, row in enumerate(text.split()) for x, ch in enumerate(row)}
    start = next(p for p, ch in grid.items() if ch == "^")
    return grid, start


def walk(grid: dict[complex, str], pos: complex, d: complex = -1j):
    while True:
        yield pos, d
        ahead = grid.get(pos + d)
        if ahead is None:
            return
        if ahead == "#":
            d *= 1j
        else:
            pos += d


def part1(text: str) -> int:
    grid, start = parse(text)
    return len({pos for pos, _ in walk(grid, start)})

This is shorter, not faster. On a generated 130 by 130 map with a path of about 5,000 cells, the size write-ups report for real inputs, it takes about 3.5 ms against about 1 ms for step 1. Neither number matters here.

Part 2: one more obstacle

Now add one obstacle, anywhere except on the guard’s start, so that she never leaves: she walks in a circle for ever. Count the cells where that works. In the example there are 6.

The first thing to settle is what “a loop” means in code. Standing on a cell she has stood on before isn’t it, since her path crosses itself. Standing on it again facing the same way is: from there everything she does repeats. So a walk keeps a set of (position, heading) states and stops when one comes round again.

Part 2 on the example: 40 trials, one for each cell of the original path. Gold marks the six cells that trap her.

Step 1: try every empty cell

def loops(grid: dict[complex, str], pos: complex, d: complex) -> bool:
    seen = set()
    for state in walk(grid, pos, d):
        if state in seen:
            return True
        seen.add(state)
    return False


def part2(text: str) -> int:
    grid, start = parse(text)
    count = 0
    for cell, ch in grid.items():
        if ch != ".":
            continue
        grid[cell] = "#"
        count += loops(grid, start, -1j)
        grid[cell] = "."
    return count

It’s correct, and it’s slow: about 16,000 empty cells on a 130 by 130 map, each followed by a walk of thousands of steps. On a generated map that size it took about 25 seconds.

Step 2: only cells on her path

An obstacle on a cell she never walks through is never in front of her, so she takes the same path as before and leaves. Only the cells of the original path can change anything, which is the part 1 answer minus the start:

def part2(text: str) -> int:
    grid, start = parse(text)
    path = {pos for pos, _ in walk(grid, start)} - {start}
    count = 0
    for cell in path:
        grid[cell] = "#"
        count += loops(grid, start, -1j)
        grid[cell] = "."
    return count

About 5,000 candidates instead of 16,000, and the time drops to about 5 seconds on the same generated map.

Step 3: start from just before the obstacle

Every trial still walks from the start. But until the guard first reaches the new obstacle, it makes no difference to her: that part of the walk is the same as in part 1. So walk the original path once, and each time she is about to step onto a cell for the first time, put the obstacle there and run the trial from where she stands:

def part2(text: str) -> int:
    grid, start = parse(text)
    tried = {start}
    count = 0
    for pos, d in walk(grid, start):
        cell = pos + d
        if grid.get(cell) != "." or cell in tried:
            continue
        tried.add(cell)
        grid[cell] = "#"
        count += loops(grid, pos, d)
        grid[cell] = "."
    return count

The tried set is easy to leave out and it matters. Her path crosses itself, so she can be about to enter the same cell more than once, and only the first time is a valid starting point: by the second, an obstacle there would already have turned her away earlier. Without it the example still gives 6, which is what makes it a nasty bug; the tests compare this step with step 1 on 300 random small maps, and without tried five of them disagree.

The new trial’s seen set starts empty even though she has been walking for a while. That’s fine: if she later comes back to one of those earlier states, she then repeats the walk that led to the obstacle, and that repeats a state of the trial itself.

About 1 second now.

Step 4: jump whole straight runs

What’s left is walking cell by cell along the same rows and columns, trial after trial. Where a straight run ends depends only on the cell and the heading, so it can be worked out once for the whole map: for each cell and heading, the cell just before the next obstacle, or None if she walks off the map. Going through the cells from the far end backwards, each answer is the one of the cell ahead:

def jumps(grid: dict[complex, str]) -> dict[tuple[complex, complex], complex | None]:
    stop = {}
    for d in (-1j, 1, 1j, -1):
        for pos in sorted(grid, key=lambda p: -(p.real * d.real + p.imag * d.imag)):
            if grid[pos] == "#":
                continue
            ahead = grid.get(pos + d)
            stop[pos, d] = None if ahead is None else pos if ahead == "#" else stop[pos + d, d]
    return stop

The table doesn’t know about the new obstacle, so each run checks whether the obstacle is straight ahead and no farther than where the run would end. Multiplying by the conjugate of a unit step turns an offset into “how far along d” (the real part) and “how far to the side” (the imaginary part), and an obstacle is on the run when the second is 0 and the first is between 1 and the run’s length:

def loops_jumping(stop, block: complex, pos: complex, d: complex) -> bool:
    seen = set()
    while True:
        end = stop[pos, d]
        off = (block - pos) * d.conjugate()
        ahead = off.real if off.imag == 0 else -1
        if ahead > 0 and (end is None or ahead <= ((end - pos) * d.conjugate()).real):
            end = block - d
        elif end is None:
            return False
        if (end, d) in seen:
            return True
        seen.add((end, d))
        pos, d = end, d * 1j


def part2(text: str) -> int:
    grid, start = parse(text)
    stop = jumps(grid)
    tried = {start}
    count = 0
    for pos, d in walk(grid, start):
        cell = pos + d
        if grid.get(cell) != "." or cell in tried:
            continue
        tried.add(cell)
        count += loops_jumping(stop, cell, pos, d)
    return count

The guard is now only looked at where she turns, so only those states go in seen. That’s still a correct loop test: she can’t loop without turning, so any loop passes through a turn, and that turn’s state repeats.

On the generated maps this takes about 90 ms, a few hundred times faster than step 1. The order of the steps matters for that number: each one removes a different kind of waste (cells that can’t matter, the walk before the obstacle, the cells in the middle of a run).

The timings are CPU time on two generated 130 by 130 maps with 800 obstacles, on a busy machine, so they are rounded. Random obstacles alone gave paths of only a few hundred cells, so the generator lays a long path first and scatters the rest of the obstacles off it. Both maps came out with about 1,400 loop cells. The tests check each part 2 step against step 1 on random small maps and on generated maps with long paths.

All of this was checked on the puzzle’s example and on generated inputs, not on a puzzle input of my own.