Advent of Code 2024, Day 22

In part 2, I lost time because I curiously misunderstood the definition of the prices at first: I thought they were the number of 1’s in the decimal representation of a secret number. (I probably misread “ones digit” as “ones’ number”.)

My solution runs somewhat slow, at 1 second for part 1 and 3 seconds for part 2. Replacing the multiplications and divisions with bit shifts, and the modulo operations with bitwise and operations, reduces the time for part 2 from 3.3 seconds to 2.7 seconds on my machine, but I find this negligible.

Part 1

import sys

def next(n):
    n = (n ^ (n * 64)) % 16777216
    n = (n ^ (n // 32)) % 16777216
    n = (n ^ (n * 2048)) % 16777216
    return n

with open(sys.argv[1]) as f:
    ns = [int(line.strip()) for line in f]

s = 0
for n in ns:
    for _ in range(2000):
        n = next(n)
    s += n
print(s)

Part 2

import sys

def next(n):
    n = (n ^ (n * 64)) % 16777216
    n = (n ^ (n // 32)) % 16777216
    n = (n ^ (n * 2048)) % 16777216
    return n

def price(n):
    return n % 10

def step(old_n, old_p):
    n = next(old_n)
    p = price(n)
    d = p - old_p
    return n, p, d

def tuples_for(buyer):
    r = {}
    n, p, a = buyer, price(buyer), 0
    n, p, b = step(n, p)
    n, p, c = step(n, p)
    n, p, d = step(n, p)
    r[(a, b, c, d)] = p
    for _ in range(2000-3):
        a, b, c = b, c, d
        n, p, d = step(n, p)
        if (a, b, c, d) not in r:
            r[(a, b, c, d)] = p
    return r

with open(sys.argv[1]) as f:
    ns = [int(line.strip()) for line in f]

d = {}
for n in ns:
    new = tuples_for(n)
    for k, v in new.items():
        d[k] = d.get(k, 0) + v
print(max(d.values()))

2024-12-22

Proxy Information
Original URL
gemini://dkalak.de/aoc/22.gmi
Status Code
Success (20)
Meta
text/gemini; lang=en
Capsule Response Time
116.854887 milliseconds
Gemini-to-HTML Time
0.562696 milliseconds

This content has been proxied by September (ba2dc).