← blog

Twenty-Five Days · day 13 · both parts

Day 13: Claw Contraption

the puzzle ↗ #aoc-2024#python

Two buttons, two axes, one prize. Part 1 can be searched. Part 2 can’t, and it turns out it never needed searching: there’s only ever one answer to check.

The puzzle, in my words

A claw machine has two buttons. Each press of A moves the claw a fixed amount along X and along Y and costs 3 tokens; each press of B moves it by a different fixed amount and costs 1. The claw has to end exactly on the prize. For every machine that can be won with at most 100 presses of each button, take the cheapest way, and add up the tokens.

In the example’s first machine A moves (94, 34), B moves (22, 67) and the prize is at (8400, 5400): 80 presses of A and 40 of B land on it, for 80 × 3 + 40 = 280 tokens. The third machine takes 38 A and 86 B, 200 tokens; the second and fourth can’t be won at all. The answer is 480.

Part 1: try the presses

Part 1 on the example: for each number of A presses, X says how many B presses are left. The dotted line is the prize’s X.

Step 1: the first version

Every machine is six numbers, so pull them out with a regular expression and don’t bother with the words around them. Then try every pair of press counts up to 100 and keep the cheapest one that lands on the prize:

import re


def machines(text: str) -> list[tuple[int, ...]]:
    """Each machine as (ax, ay, bx, by, px, py)."""
    return [tuple(map(int, re.findall(r"\d+", block))) for block in text.split("\n\n")]


def part1(text: str) -> int:
    total = 0
    for ax, ay, bx, by, px, py in machines(text):
        best = None
        for a in range(101):
            for b in range(101):
                if a * ax + b * bx == px and a * ay + b * by == py:
                    cost = 3 * a + b
                    if best is None or cost < best:
                        best = cost
        if best is not None:
            total += best
    return total

That’s 10,201 tries a machine. On a generated input of 320 machines it takes about 80 ms.

Step 2: B is forced

Once the number of A presses is chosen there’s no choice left for B: along X, it has to cover the remaining px - a * ax in whole steps of bx. divmod gives the number of steps and what’s left over; anything left over means the claw can’t stop on the prize’s X, and if nothing is, Y is a single check. That’s the clip above: one path per number of A presses, each ending on the dotted line.

def part1(text: str) -> int:
    total = 0
    for ax, ay, bx, by, px, py in machines(text):
        costs = []
        for a in range(101):
            b, rest = divmod(px - a * ax, bx)
            if rest == 0 and 0 <= b <= 100 and a * ay + b * by == py:
                costs.append(3 * a + b)
        total += min(costs, default=0)
    return total

When A alone already overshoots, px - a * ax is negative and b comes out negative too, so the 0 <= b check covers it. min(..., default=0) scores a machine that can’t be won as 0 instead of raising on an empty list. On the same generated input this takes about 2 ms instead of 80.

Part 2: ten trillion further

Now every prize is 10000000000000 further along both X and Y, and there’s no limit on presses. On the example only the second and fourth machines can be won, with around a hundred billion presses of each button, for 875318608908 tokens in all. That total is what the code below computes; the presses check out when put back into both axes.

Part 2 on the example. A line out along A and a line back along B cross at exactly one point; the machine wins only if that point is a whole number of presses.

Step 1: two equations, one answer

Step 2 of part 1 would now loop about 10^11 times a machine. But look at what it’s searching: the two axes are two equations in two unknowns,

a * ax + b * bx = px
a * ay + b * by = py

and a pair of linear equations like that has exactly one solution unless the buttons push in the same direction. Cramer’s rule writes it down: with det = ax * by - ay * bx, a = (px * by - py * bx) / det and b = (ax * py - ay * px) / det. In the clip, that’s the point where the line out along A meets the line back along B.

So “fewest tokens” has nothing left to choose: there’s one candidate, and the machine is won if both press counts are whole and not negative. divmod checks “whole” with integers alone, so there’s no float rounding to worry about and no tolerance to pick. Python’s integers have no fixed size, so the products, around 10^15 here, don’t overflow either.

OFFSET = 10_000_000_000_000


def tokens(ax, ay, bx, by, px, py) -> int:
    det = ax * by - ay * bx
    if det == 0:
        raise ValueError("A and B move along the same line")
    a, ra = divmod(px * by - py * bx, det)
    b, rb = divmod(ax * py - ay * px, det)
    if ra or rb or a < 0 or b < 0:
        return 0
    return 3 * a + b


def part2(text: str) -> int:
    return sum(
        tokens(ax, ay, bx, by, px + OFFSET, py + OFFSET)
        for ax, ay, bx, by, px, py in machines(text)
    )

det can be negative (it is for two of the example’s machines). Python’s divmod rounds the quotient down and gives the remainder the divisor’s sign, but the remainder is still 0 exactly when the division is exact, and the a < 0 or b < 0 check doesn’t care which way the signs came out. With no loop left, the generated input of 320 machines takes about half a millisecond. (Timings here are rough: the computer was busy with other work while they ran.)

Step 2: when the buttons are parallel

Step 1 refuses one case: det == 0, where both buttons move the claw in the same direction. Then there’s either no way to win or many, and “fewest” is a real question. At least one public write-up says real inputs never contain such a machine; I couldn’t check that here, and the example doesn’t have one either. It’s not exotic, though: the first random input I generated for the timings had one by chance, and step 1 raised on it.

It isn’t much code to answer it properly. The claw can only ever move along one line through the start, so the prize has to be on that line; after that, X alone decides. Among the solutions of a * ax + b * bx = px, each extra press of A changes the cost by the same amount, so the cheapest is at one end: as few A presses as possible if B covers at least as much ground per token (3 * bx >= ax), otherwise as few B presses as possible. Which counts leave a whole number for the other button repeats every bx (or ax) tries, so a short loop finds the first one or shows there isn’t one:

def tokens(ax, ay, bx, by, px, py) -> int:
    det = ax * by - ay * bx
    if det:
        a, ra = divmod(px * by - py * bx, det)
        b, rb = divmod(ax * py - ay * px, det)
        return 0 if ra or rb or a < 0 or b < 0 else 3 * a + b
    if ax * py != ay * px:  # the prize is off the only line the claw can follow
        return 0
    if 3 * bx >= ax:
        for a in range(bx):
            b, rest = divmod(px - a * ax, bx)
            if b < 0:
                break
            if rest == 0:
                return 3 * a + b
    else:
        for b in range(ax):
            a, rest = divmod(px - b * bx, ax)
            if a < 0:
                break
            if rest == 0:
                return 3 * a + b
    return 0

This leans on the button moves being positive, which the input’s X+n, Y+n format gives. Part 1’s search never needed the special case: it tries every number of A presses, so it already picks the cheapest when there’s more than one. The tests check the parallel branch against a direct search over every number of A presses on 300 random parallel machines, and Cramer against the same search on 300 machines that aren’t parallel.

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