← blog

Twenty-Five Days · day 22 · both parts

Day 22: Monkey Market

the puzzle ↗ #aoc-2024#python

Part 1 is a random number generator run 2000 times, and the interesting part is that it doesn’t have to be run: every stage is “XOR with a shifted copy of yourself”, and that reduces it to 24 precomputed numbers. Part 2 needs every number the generator makes, and the trick there is to total every possible answer in a single pass instead of trying them one by one.

The puzzle, in my words

Each buyer starts with a secret number, and a secret turns into the next in three stages: multiply by 64, divide by 32 (rounding down), multiply by 2048. After each stage the result is XORed into the secret, and the secret is reduced modulo 16777216. Starting from 123, the next secrets are 15887950, 16495136, 527345, and so on.

Part 1: make 2000 new secrets for each buyer and add up where they end. For the example buyers 1, 10, 100 and 2024 that’s 8685429 + 4700978 + 15273692 + 8667524 = 37327623.

Part 1: 2000 secrets per buyer

Part 1. The first secret after 123 is worked stage by stage; the four example buyers then make 2000 new secrets each.

Step 1: the first version

Write the rules down as they’re given: mix is XOR, prune is %, and the three stages in order.

def seeds(text: str) -> list[int]:
    return [int(n) for n in text.split()]


def mix(value: int, secret: int) -> int:
    return value ^ secret


def prune(secret: int) -> int:
    return secret % 16777216


def next_secret(secret: int) -> int:
    secret = prune(mix(secret * 64, secret))
    secret = prune(mix(secret // 32, secret))
    secret = prune(mix(secret * 2048, secret))
    return secret


def part1(text: str) -> int:
    total = 0
    for secret in seeds(text):
        for _ in range(2000):
            secret = next_secret(secret)
        total += secret
    return total

That’s 2000 calls per buyer. On a generated input of 2000 buyers it takes about 0.9 s.

Step 2: every number is a power of two

64 is 2 ** 6, 32 is 2 ** 5, 2048 is 2 ** 11 and 16777216 is 2 ** 24. So the stages are shifts: << 6, >> 5, << 11, and the prune keeps the low 24 bits, & 0xFFFFFF. Python’s integers never overflow, so the mask is what keeps a shifted value from growing; it is still needed.

The secret is always below 2 ** 24, so in an XOR only the shifted copy can bring in higher bits. Masking the copy before the XOR therefore gives the same result as pruning after it. And the middle stage only makes the copy smaller, so it needs no mask at all:

MASK = 0xFFFFFF


def evolve(secret: int) -> int:
    secret ^= (secret << 6) & MASK
    secret ^= secret >> 5
    secret ^= (secret << 11) & MASK
    return secret


def part1(text: str) -> int:
    total = 0
    for secret in seeds(text):
        for _ in range(2000):
            secret = evolve(secret)
        total += secret
    return total

Same answers, in about 0.5 s instead of 0.9 s on the same generated input (I’d put most of that down to the three helper calls per stage being gone; I haven’t measured the parts separately). The bigger gain is that the shape of the generator is now visible.

Step 3: jump 2000 steps at once

Every stage is the secret XORed with a shifted copy of itself, and shifting, masking and XOR all treat each bit on its own. So the whole step is linear over bits: evolving a ^ b gives the same as evolving a and b separately and XORing the results. That holds for one step, so it holds for 2000.

A secret is the XOR of its set bits, and there are only 24 possible bits. Evolve each single bit (1, 2, 4, … up to 2 ** 23) 2000 times, once; then any buyer’s 2000th secret is the XOR of the results for the bits it has set:

from functools import cache


@cache
def bit_images(steps: int) -> tuple[int, ...]:
    images = []
    for bit in range(24):
        s = 1 << bit
        for _ in range(steps):
            s = evolve(s)
        images.append(s)
    return tuple(images)


def jump(secret: int, steps: int = 2000) -> int:
    out = 0
    for bit, image in enumerate(bit_images(steps)):
        if secret >> bit & 1:
            out ^= image
    return out


def part1(text: str) -> int:
    return sum(jump(secret) for secret in seeds(text))

The setup is 24 × 2000 = 48,000 evolutions, and after that each buyer costs at most 24 XORs instead of 2000 evolutions. On the generated input of 2000 buyers that’s about 8 ms, setup included, against 0.5 s. @cache keeps the 24 images, so a second call with the same steps doesn’t rebuild them.

The tests check jump against plain evolving on 200 random secrets and step counts, and all three steps against each other on random inputs.

Steps 2 and 3 assume every starting secret is below 2 ** 24, as a pruned number is: evolve only masks the shifted copy, so a larger seed would keep its high bits. The example’s are tiny; that real inputs stay in range is an assumption here, not something checked.

Part 2: the best moment to sell

Now a buyer’s price is the last digit of each secret, the starting one included, so 2000 new secrets make 2001 prices and 2000 changes between them. You pick one run of four consecutive changes, the same for every buyer, and each buyer sells the first time that run appears in their changes, at the price that ends it; never, if it doesn’t appear. Which run earns the most in total?

123’s first ten prices are 3, 0, 6, 5, 4, 4, 6, 4, 4, 2; the run -1, -1, 0, 2 would sell there at 6. In the part 2 example (buyers 1, 2, 3 and 2024) the best run is -2, 1, -1, 3: buyers 1 and 2 sell at 7, buyer 3 never sees it, buyer 2024 sells at 9. That’s 23.

Part 2. First the ten prices of 123 and the first-seen price of each run of four changes; then the example buyers, watching for -2 1 -1 3.

Step 1: a table of first sightings

Trying every run against every buyer is 19⁴ = 130,321 runs times a scan of 2000 changes per buyer: far too slow. Turn it round instead. Walk each buyer’s changes once, and for every window of four, the first time it shows up, that buyer would sell at the price after it. Add that price to the window’s total. After all buyers, every run’s total is known, and the answer is the biggest:

from collections import Counter
from itertools import pairwise


def part2(text: str) -> int:
    totals = Counter()
    for secret in seeds(text):
        prices = [secret % 10]
        for _ in range(2000):
            secret = evolve(secret)
            prices.append(secret % 10)
        changes = [b - a for a, b in pairwise(prices)]
        seen = set()
        for i in range(len(changes) - 3):
            window = tuple(changes[i : i + 4])
            if window not in seen:
                seen.add(window)
                totals[window] += prices[i + 4]
    return max(totals.values())

The seen set is what makes it the first sighting: a later repeat of the same run is ignored for that buyer. Part 1’s jump is no help here, since every one of the 2000 prices is needed. This takes about 2 s on the generated input of 2000 buyers.

Step 2: the run as one rolling number

Each change is between -9 and 9, so change + 9 is a digit in base 19, and four changes make a number below 19 ** 4 = 130321. Keep that number as you go: multiply by 19 to make room for the new change, and % 19 ** 4 drops the oldest, the way appending a digit and keeping the last four would in base 10. That removes the price list, the slicing and the tuples, and the totals fit in a plain list indexed by the key:

def part2(text: str) -> int:
    size = 19**4
    totals = [0] * size
    for secret in seeds(text):
        seen = set()
        key = 0
        price = secret % 10
        for i in range(1, 2001):
            secret = evolve(secret)
            new = secret % 10
            key = (key * 19 + new - price + 9) % size
            price = new
            if i >= 4 and key not in seen:
                seen.add(key)
                totals[key] += price
    return max(totals)

The key starts at 0 for each buyer, so it only stands for four real changes from the fourth one on; i >= 4 makes sure nothing is counted before that. About 1 s on the same input, half of step 1. The work left is the 4 million evolutions themselves, which pure Python can’t skip. The tests check this version against step 1 on random inputs, and a brute force over every run that occurs in the example agrees that -2, 1, -1, 3 and 23 are the best.

One thing the example can’t decide is whether the starting secret’s digit counts as the first price: leaving it out still gives -2, 1, -1, 3 and 23. The one write-up I found that lists 123’s prices starts them with its own 3, so the code includes it.

The timings are from generated inputs of 2000 buyers with random starting secrets (best of a few runs), so they’re a guide to the order of magnitude, not a benchmark. All of this was checked on the puzzle’s examples and on generated inputs, not on a puzzle input of my own.