advent_of_code/2024/day17/main.py
2024-12-17 17:32:01 -05:00

123 lines
2.8 KiB
Python

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 run_program(r, p):
pc = 0
out = 0
while True:
operands = [0,1,2,3,r["A"],r["B"],r["C"], 7]
co = operands[p[pc+1]]
lo = p[pc+1]
match p[pc]:
case 0:
r["A"] = r["A"] >> co
pc += 2
case 1:
r["B"] = r["B"] ^ lo
pc += 2
case 2:
r["B"] = co % 8
pc += 2
case 3:
if r["A"] == 0:
pc += 2
else:
pc = lo
return out, pc
case 4:
r["B"] = r["B"] ^ r["C"]
pc += 2
case 5:
out = int(co % 8)
pc += 2
case 6:
r["B"] = r["A"] >> co
pc += 2
case 7:
r["C"] = r["A"] >> co
pc += 2
def part_one(registers, program):
pc = 0
out = []
looping = True
while looping:
if pc > len(program)-1:
looping = False
break
else:
o, pc = run_program(registers, program)
out.append(o)
print("P1: ", str(out).strip('[]').replace(" ", ""))
return out
def part_two(r, p):
pc = 0
A = 0
looping = True
p_copy = p.copy()
p_copy.reverse()
R = {"A": 0, "B": 0, "C": 0}
for count, op in enumerate(p_copy):
i = 0
while True:
# print(A)
out = []
r = copy.deepcopy(R)
r["A"] = A+i
# out = part_one(r, p)
o = -1
pc = 0
while pc == 0:
o, pc = run_program(r, p)
out.append(o)
# print(o)
# if c > 0 and o != p[-(count-c)]:
# failed = True
# break
# c+=1
# if not failed:
if out == p[:count+1]:
print(out)
A = (A+i)<<3
break
i+=1
# else:
# A += 1
A = A>>3
R["A"]=A
print("P2: ", A, R["A"], out)
part_one(R, p)
def main():
program = []
registers = {}
pos = [0,0]
contents = file2list("test.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()