|
| 1 | +from GhostyUtils import aoc |
| 2 | +from dataclasses import dataclass |
| 3 | +import operator |
| 4 | +from typing import Callable |
| 5 | + |
| 6 | + |
| 7 | +@dataclass |
| 8 | +class Registers: |
| 9 | + A: int |
| 10 | + B: int |
| 11 | + C: int |
| 12 | + |
| 13 | + |
| 14 | +def combo(operand: int, regs: Registers) -> int: |
| 15 | + match operand: |
| 16 | + case 0: return 0 |
| 17 | + case 1: return 1 |
| 18 | + case 2: return 2 |
| 19 | + case 3: return 3 |
| 20 | + case 4: return regs.A |
| 21 | + case 5: return regs.B |
| 22 | + case 6: return regs.C |
| 23 | + case 7: assert False |
| 24 | + |
| 25 | + |
| 26 | +def process(program: list[int], regs: Registers, output: Callable): |
| 27 | + i_ptr = 0 |
| 28 | + |
| 29 | + while True: |
| 30 | + if i_ptr >= len(program): |
| 31 | + break |
| 32 | + |
| 33 | + instr = program[i_ptr] |
| 34 | + operand = program[i_ptr+1] |
| 35 | + |
| 36 | + match instr: |
| 37 | + case 0: # adv (A division by combo operand, store in A) |
| 38 | + regs.A = regs.A // (2 ** combo(operand, regs)) |
| 39 | + i_ptr += 2 |
| 40 | + case 1: # bxl (bitwise xor of B and literal operand, store in B) |
| 41 | + regs.B = operator.xor(regs.B, operand) |
| 42 | + i_ptr += 2 |
| 43 | + case 2: # bst (combo operand modulo 8, store in B) |
| 44 | + regs.B = combo(operand, regs) % 8 |
| 45 | + i_ptr += 2 |
| 46 | + case 3: # jnz (jump to literal operand if A non-zero) |
| 47 | + if regs.A == 0: |
| 48 | + i_ptr += 2 |
| 49 | + else: |
| 50 | + i_ptr = operand |
| 51 | + case 4: # bxc (bitwise xor of B and C, store in B) |
| 52 | + regs.B = operator.xor(regs.B, regs.C) |
| 53 | + i_ptr += 2 |
| 54 | + case 5: # out (output combo operand modulo 8) |
| 55 | + output(combo(operand, regs) % 8) |
| 56 | + i_ptr += 2 |
| 57 | + case 6: # bdv (A division by combo operand, store in B) |
| 58 | + regs.B = regs.A // (2 ** combo(operand, regs)) |
| 59 | + i_ptr += 2 |
| 60 | + case 7: # cdv (A division by combo operand, store in C) |
| 61 | + regs.C = regs.A // (2 ** combo(operand, regs)) |
| 62 | + i_ptr += 2 |
| 63 | + |
| 64 | + |
| 65 | +def read_regs(registers: str) -> Registers: |
| 66 | + a, b, c = (r.split(': ') for r in registers.splitlines()) |
| 67 | + regs = Registers(int(a[1]), int(b[1]), int(c[1])) |
| 68 | + return regs |
| 69 | + |
| 70 | + |
| 71 | +def main(): |
| 72 | + registers, program = (section.strip() for section in aoc.read_sections()) |
| 73 | + regs = read_regs(registers) |
| 74 | + program = list(map(int, program.split(': ')[1].split(','))) |
| 75 | + |
| 76 | + output = [] |
| 77 | + process(program, regs, output=output.append) |
| 78 | + print(f"p1: {','.join(map(str, output))}") |
| 79 | + |
| 80 | + |
| 81 | +if __name__ == "__main__": |
| 82 | + main() |
0 commit comments