Skip to content
advent of code 2020

day 08

handheld halting

approach

the program is a list of (instruction, argument) pairs, and exec runs it with an accumulator and a program counter, remembering every address it has visited. it stops either when an address repeats (a loop) or when the counter runs off the end (a halt), and returns the accumulator with that status.

part 1 is the accumulator at the moment the loop is detected. part 2 tries flipping each jmp to nop and vice versa, one at a time, runs the program, restores the instruction, and returns the accumulator of the first variant that halts.

the trick

a visited set is enough to detect the loop, which also makes brute-forcing every single-instruction swap cheap.

python
    while pc < len(l) and pc not in s:
        ins, arg = l[pc]
        s.add(pc)
        if ins == "jmp":
            pc += arg
            continue
        elif ins == "acc":
            a += arg
        pc += 1
    return (a, "HALT" if pc >= len(l) else "LOOP")