← blog

Twenty-Five Days · day 11 · both parts

Day 11: Plutonian Pebbles

the puzzle ↗ #aoc-2024#python

The classic exponential trap. Part 1 is a list that you rebuild 25 times. Part 2 asks for 75 rebuilds, and the list would need hundreds of terabytes. The interesting part is that the answer only needs how many stones there are, and the stones keep repeating the same few numbers.

The puzzle, in my words

A line of stones, each with a number on it. Every blink, each stone changes by the first rule that fits: a 0 becomes a 1; a number with an even number of digits splits into two stones, its left half and its right half (1000 becomes 10 and 0, with no leading zeros); anything else is multiplied by 2024. Count the stones after 25 blinks.

The example starts with 125 17. One blink gives 253000 1 7 (125 times 2024, and 17 split in two), the next gives 253 0 2024 14168, and after 6 blinks there are 22 stones. After 25 there are 55312.

Part 1: rebuild the list

Part 1 on 125 17. Green: times 2024, red: a split, gold: 0 to 1. The bars are on a log scale, a faint line per power of ten.

Step 1: the first version

Keep the stones in a list and build the next list every blink, checking the rules in order. str gives the digits, and int takes care of the leading zeros: int("00") is 0.

def part1(text: str) -> int:
    stones = [int(n) for n in text.split()]
    for _ in range(25):
        new = []
        for stone in stones:
            digits = str(stone)
            if stone == 0:
                new.append(1)
            elif len(digits) % 2 == 0:
                half = len(digits) // 2
                new.append(int(digits[:half]))
                new.append(int(digits[half:]))
            else:
                new.append(stone * 2024)
        stones = new
    return len(stones)

Step 2: one function for one stone

The rules are about a single stone, so they can live in a function that says what one stone becomes: a tuple of one stone or two. Then a blink is a comprehension with two for clauses, which flattens those tuples into the next list:

def blink(stone: int) -> tuple[int, ...]:
    if stone == 0:
        return (1,)
    digits = str(stone)
    half, odd = divmod(len(digits), 2)
    if odd:
        return (stone * 2024,)
    return int(digits[:half]), int(digits[half:])


def part1(text: str) -> int:
    stones = [int(n) for n in text.split()]
    for _ in range(25):
        stones = [new for stone in stones for new in blink(stone)]
    return len(stones)

This is tidier, not faster. On generated lines of eight numbers (my guess at the shape of a real input; I couldn’t check it), step 1 takes 43 to 62 ms and step 2 about 30% more, the price of a function call per stone. blink earns its place in part 2.

Part 2: count, don’t list

Same rules, 75 blinks. The puzzle gives no answer for the example this time; both versions below give 65601038650482 for 125 17, and a public write-up reports the same number.

The list can’t get there. It grows about 1.5 times per blink: on the example it is 55 thousand stones at blink 25, 29 million at 40, 1.9 billion at 50 and 65.6 trillion at 75. A Python list stores a pointer per element, 8 bytes on a 64-bit build (sys.getsizeof([None] * 10**6) is just over 8 MB), so that last list would be over 500 TB before counting the numbers themselves. Timed with step 2 on another generated line, 10 2000 6220 8 0 9953 8 1000, 25 blinks take 96 ms, 30 take 0.8 s and 35 take 6.6 s, eight times longer every five blinks; at that rate 75 would take years (extrapolated, not run).

Part 2 on 125 17: the stones grouped by number, then all 75 blinks. Pink: stones. Green: different numbers. Log scale.

Step 1: a Counter instead of a list

Two things make the list unnecessary. The question is only how many stones there are, so their order doesn’t matter. And what a stone turns into depends on its own number alone, never on its neighbours. So equal stones can be handled together: keep a Counter from each number to how many stones carry it, and each blink, pass every number’s count on to what it becomes.

from collections import Counter


def part2(text: str) -> int:
    counts = Counter(int(n) for n in text.split())
    for _ in range(75):
        new = Counter()
        for stone, n in counts.items():
            for after in blink(stone):
                new[after] += n
        counts = new
    return counts.total()

Counter.total() (Python 3.10+) adds up the counts. A missing key reads as 0, so new[after] += n needs no check.

This only helps if the numbers repeat, and they repeat a lot. On the example, the 22 stones of blink 6 carry only 15 different numbers, and from blink 17 on there are always exactly 54 different numbers, every blink up to 75, while the stones go from two thousand to 65 trillion. Why it levels off is easy to believe: big numbers split into smaller ones, and single digits go through 2024 and split back into single digits. But I only observed it, I didn’t prove it. On the two generated lines with larger starting numbers it is still creeping up at blink 75 (3,750 and 3,795 different numbers), and both reach 3,811 by blink 100 and stay there to blink 120, which is the same total someone reports as every number their real input can produce. Either way each blink is a few thousand dictionary updates: 51 to 55 ms for all 75 blinks on those lines, about what the list needed for 25.

Step 2: remember each stone’s answer

The same idea from the other side. How many stones a stone with number s becomes after k blinks depends only on s and k: it’s 1 when k is 0, and otherwise the sum of that count for each stone s turns into, with k - 1. Written as a recursive function, it would recompute the same (s, k) pairs again and again; functools.cache (Python 3.9+) stores each answer the first time and returns it after that.

from functools import cache


def part2(text: str) -> int:
    @cache
    def count(stone: int, k: int) -> int:
        if k == 0:
            return 1
        return sum(count(after, k - 1) for after in blink(stone))

    return sum(count(int(n), 75) for n in text.split())

The cached function is defined inside part2 on purpose. At module level its cache would outlive the call, and a second call, say in a timing loop, would just read back stored answers. On the example it stores 3,645 pairs; the recursion goes 75 calls deep, and with the generator expression at each level it needs a recursion limit somewhere between 150 and 160 (I tried), well inside Python’s default of 1,000.

It reads more like the definition than step 1 does, and it’s a little slower here: 88 to 91 ms on the same generated lines, each call starting with an empty cache. Both are many orders of magnitude from the list. The tests check both against the list for up to 15 blinks on random lines (with zeros, repeats and numbers like 1000), and against each other at 75.

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