advent_of_code/2024/day17/main.py

120 lines
3.5 KiB
Python
Raw Normal View History

import re
import sys
import copy
# import numpy as np
import os
from warnings import showwarning
sys.path.insert(1, os.path.abspath('../../'))
from python_tools.aoc_utils import *
def part_one(registers, program):
pc = 0
out = []
looping = True
last_state = 0
current_state = [registers, program, pc]
while looping:
if pc > len(program)-1 or current_state == last_state:
looping = False
break
else:
operands = [0,1,2,3,registers["A"],registers["B"],registers["C"], 7]
co = operands[program[pc+1]]
lo = program[pc+1]
match program[pc]:
case 0:
registers["A"] = registers["A"] >> co
pc += 2
case 1:
registers["B"] = registers["B"] ^ lo
pc += 2
case 2:
registers["B"] = co % 8
pc += 2
case 3:
if registers["A"] == 0:
pc += 2
else:
pc = lo
case 4:
registers["B"] = registers["B"] ^ registers["C"]
pc += 2
case 5:
out.append(int(co % 8))
pc += 2
case 6:
registers["B"] = registers["A"] >> co
pc += 2
case 7:
registers["C"] = registers["A"] >> co
pc += 2
print("P1: ", str(out).strip('[]').replace(" ", ""))
def part_two(r, p):
pc = 0
out = []
looping = True
last_state = 0
current_state = [registers, program, pc]
while looping:
if pc > len(program)-1 or current_state == last_state:
looping = False
break
else:
operands = [0,1,2,3,registers["A"],registers["B"],registers["C"], 7]
co = operands[program[pc+1]]
lo = program[pc+1]
match program[pc]:
case 0:
registers["A"] = registers["A"] >> co
pc += 2
case 1:
registers["B"] = registers["B"] ^ lo
pc += 2
case 2:
registers["B"] = co % 8
pc += 2
case 3:
if registers["A"] == 0:
pc += 2
else:
pc = lo
case 4:
registers["B"] = registers["B"] ^ registers["C"]
pc += 2
case 5:
out.append(int(co % 8))
pc += 2
case 6:
registers["B"] = registers["A"] >> co
pc += 2
case 7:
registers["C"] = registers["A"] >> co
pc += 2
print("P2: ", count)
def main():
program = []
registers = {}
pos = [0,0]
contents = file2list("input.txt")
for row, i in enumerate(contents):
if "Register" in i:
a = i.split(":")
registers[a[0].replace("Register ", "")] = int(a[1].strip())
elif "Program" in i:
i = i.replace("Program: ", "")
program = list(map(int, i.split(",")))
print(registers, program)
part_one(registers.copy(), program)
part_two(registers.copy(), program)
if __name__ == "__main__":
main()