Skip to content
advent of code 2022

day 10

cathode-ray tube

approach

instead of stepping cycle by cycle, the program is turned into a history of (cycle, x) pairs, recorded only when an addx changes the register. x_at binary-searches that history for the last change at or before a given cycle.

part 1 sums cycle times register for the six sampled cycles. part 2 goes through 240 cycles, lights a pixel when the sprite at x covers the current column, and prints the screen in rows of 40, which spell out the answer.

the trick

store only the moments the register changes and look up any cycle with a binary search.

python
def x_at(history, time):
    l, r = 0, len(history) - 1
    res = 0
    while l <= r:
        m = (l + r) >> 1
        if history[m][0] <= time:
            res = history[m][1]
            l = m + 1
        else:
            r = m - 1
    return res