← blog

Twenty-Five Days · day 14 · both parts

Day 14: Restroom Redoubt

the puzzle ↗ #aoc-2024#python

Part 1 is a warm-up in modular arithmetic. Part 2 is one of the odd ones: it asks for the moment the robots draw a picture, and doesn’t say what the picture looks like. So every solution is a guess about what a picture does to the numbers, and the interesting part is finding a guess that is cheap to check.

The puzzle, in my words

Robots stand on a floor 101 tiles wide and 103 tall, and each line of the input gives one robot’s position and velocity, like p=2,4 v=2,-3: two tiles right and three up every second. The floor wraps: a robot that walks off one edge comes back in at the opposite one. Robots can share a tile.

After 100 seconds, split the floor into four quadrants along its middle column and middle row (robots exactly on those lines are in none), count the robots in each quadrant and multiply the four counts. The example is a small 11x7 floor with 12 robots: after 100 seconds the quadrants hold 1, 3, 4 and 1 robots, so the answer is 12.

Part 1: a hundred seconds later

Part 1 on the example: 100 seconds of movement, then the middle lines drop out and the quadrants are counted.

Step 1: the first version

Move every robot one second at a time, a hundred times, then sort the robots into quadrants with comparisons:

def part1(text: str, width: int = 101, height: int = 103) -> int:
    robots = []
    for line in text.splitlines():
        p, v = line.split()
        px, py = map(int, p[2:].split(","))
        vx, vy = map(int, v[2:].split(","))
        robots.append([px, py, vx, vy])
    for _ in range(100):
        for robot in robots:
            robot[0] = (robot[0] + robot[2]) % width
            robot[1] = (robot[1] + robot[3]) % height
    mid_x, mid_y = width // 2, height // 2
    quadrants = [0, 0, 0, 0]
    for x, y, _, _ in robots:
        if x < mid_x and y < mid_y:
            quadrants[0] += 1
        elif x > mid_x and y < mid_y:
            quadrants[1] += 1
        elif x < mid_x and y > mid_y:
            quadrants[2] += 1
        elif x > mid_x and y > mid_y:
            quadrants[3] += 1
    return quadrants[0] * quadrants[1] * quadrants[2] * quadrants[3]

The size is a parameter because the example’s floor is 11x7: part1(example, 11, 7) gives 12. The wrapping is a single %, because in Python the result of % takes the sign of the divisor: a robot on column 0 moving left by 3 lands on -3 % 11, which is 8, the right place. (In C or Java, -3 % 11 is -3.) Both sizes are odd, so width // 2 is exactly the middle column, and a robot on it matches none of the four conditions.

Step 2: jump instead of walking

A robot moves in a straight line, so after t seconds it is at p + t * v. Wrapping after every step and wrapping once at the end land on the same tile, because (a + b) % n is the same as (a % n + b) % n. So each robot needs one line of arithmetic, not a hundred steps:

import re


def robots(text: str) -> list[tuple[int, int, int, int]]:
    nums = [int(n) for n in re.findall(r"-?\d+", text)]
    return list(zip(nums[0::4], nums[1::4], nums[2::4], nums[3::4]))


def at(robot, t: int, width: int, height: int) -> tuple[int, int]:
    px, py, vx, vy = robot
    return (px + t * vx) % width, (py + t * vy) % height

The parser doesn’t care about the p= and v= labels: every line holds four signed integers, and slicing the flat list with a step of 4 regroups them. The quadrant becomes an index, since True and False add up as 1 and 0:

from math import prod


def part1(text: str, width: int = 101, height: int = 103) -> int:
    mid_x, mid_y = width // 2, height // 2
    quadrants = [0, 0, 0, 0]
    for robot in robots(text):
        x, y = at(robot, 100, width, height)
        if x == mid_x or y == mid_y:
            continue
        quadrants[(x > mid_x) + 2 * (y > mid_y)] += 1
    return prod(quadrants)

On a generated input of 500 robots on the full floor, step 1 takes about 5 ms and this about 0.4 ms.

Step 3: count with a Counter

A quadrant is a pair of answers, (right of the middle?, below it?), so a Counter keyed by that pair does the sorting:

from collections import Counter


def part1(text: str, width: int = 101, height: int = 103) -> int:
    mid_x, mid_y = width // 2, height // 2
    ends = (at(r, 100, width, height) for r in robots(text))
    quadrants = Counter((x > mid_x, y > mid_y) for x, y in ends if x != mid_x and y != mid_y)
    return prod(quadrants.values()) if len(quadrants) == 4 else 0

The len check is there because a Counter only holds the keys it has seen. Asking it for a missing key gives 0, but .values() leaves the key out, so a quadrant with no robots would quietly drop out of the product instead of making it 0. The tests run all three steps against each other on 200 random inputs of several sizes, small ones included, where an empty quadrant is common.

Part 2: the picture

Now, at some second, the robots line up to draw a Christmas tree, and the question is how many seconds that takes. The puzzle doesn’t describe the picture, and the example has none, so part 2 has no example answer. One write-up’s drawing of the real picture shows a solid tree with a border around it.

That makes this day hard to check without a puzzle input, and I don’t have one. So the clip and the tests use a generated input: I drew a framed tree of 380 robots, put it on the 101x103 floor at a secret second, 3906, scattered 120 more robots on other tiles, gave every robot a random velocity and ran them all back 3906 seconds. The methods below have to find that second. That shows how they work. It can’t show that they find the real picture, because the picture was built to suit them.

Part 2 on a generated input with a tree planted at second 3906 (there is no example for this part). Bars: how spread out x and y are at each second; the lowest ones are combined into one second.

The floor repeats itself, which keeps the search finite. A robot’s x is back where it started after 101 seconds, since 101 × vx is a whole number of laps; its y after 103. So the whole floor repeats every 101 × 103 = 10,403 seconds, and the picture, if there is one, shows up before that.

Step 1: the first time no robots overlap

Many people reported that on their inputs the picture is the first moment when every robot has a tile to itself. That’s easy to test with a set:

def part2(text: str, width: int = 101, height: int = 103) -> int:
    rs = robots(text)
    for t in range(width * height):
        tiles = {at(r, t, width, height) for r in rs}
        if len(tiles) == len(rs):
            return t
    return -1

It works on the generated input, where I made sure no two robots share a tile at second 3906 (and with 500 robots on 10,403 tiles, a random moment almost always has a pair that do). It took about 240 ms. But it’s a fact about how the real inputs were made, which people reported and I couldn’t check, not something the puzzle promises.

Step 2: the moment the robots bunch up

A different guess, one that doesn’t need the picture to be exact: a picture packs a lot of robots into a small area, so at that moment the robots are unusually close together. Variance measures that. n * sum(v²) - sum(v)² is n² times the variance, and with integers it’s exact, so there’s no float rounding to worry about when comparing:

def spread(values: list[int]) -> int:
    return len(values) * sum(v * v for v in values) - sum(values) ** 2


def part2(text: str, width: int = 101, height: int = 103) -> int:
    rs = robots(text)

    def bunching(t: int) -> int:
        xs, ys = zip(*(at(r, t, width, height) for r in rs))
        return spread(list(xs)) + spread(list(ys))

    return min(range(width * height), key=bunching)

min with a key returns the first of the smallest, so a tie goes to the earlier second. This one always looks at all 10,403 seconds: about a second on the generated input.

Step 3: one axis at a time

The x coordinates don’t depend on y. The x spread at second t is decided by t % 101 alone, and the y spread by t % 103, so the lowest x spread is one of the first 101 seconds and the lowest y spread one of the first 103. That is 204 checks instead of 10,403. In the clip, the x chart’s low bar is the second when the robots crowd into a vertical band, the tree’s columns lined up while its rows are still scattered:

def part2(text: str, width: int = 101, height: int = 103) -> int:
    rs = robots(text)

    def best(axis: list[tuple[int, int]], size: int) -> int:
        return min(range(size), key=lambda t: spread([(p + t * v) % size for p, v in axis]))

    tx = best([(px, vx) for px, _, vx, _ in rs], width)
    ty = best([(py, vy) for _, py, _, vy in rs], height)
    return next(t for t in range(tx, width * height, width) if t % height == ty)

The last line puts the two halves together. The answer t must have t % 101 == tx and t % 103 == ty. Because 101 and 103 have no common factor, exactly one t below 10,403 does: that’s the Chinese remainder theorem. Trying tx, tx + 101, tx + 202, … finds it in at most 103 tries. On the generated input, the x spread is lowest at 68 and the y spread at 95; 68 + 101 × 38 = 3906, and 3906 % 103 = 95.

There’s a closed form too: pow(101, -1, 103) (Python 3.8+) is the inverse of 101 modulo 103, and tx + 101 * ((ty - tx) * pow(101, -1, 103) % 103) is the same t. The tests check the two agree. The search is easier to read, and 103 tries cost nothing.

This takes about 7 ms on the generated input. Steps 2 and 3 are the same method, so the tests run both on plain random robots with no picture at all, on small floors, and check they reach the same lowest bunching.

The variance has a blind spot: it doesn’t know the floor wraps. A picture split across the left and right edges looks spread out in x, so steps 2 and 3 miss it. A test shows that on a generated input with the tree across the edge, where step 1 still finds it. The method was reported to work on real inputs, so presumably their picture doesn’t cross an edge, but that couldn’t be checked here.

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