Finished and optimized p2

This commit is contained in:
Daniel Weber 2024-12-17 19:39:35 -05:00
parent 30f4a0b942
commit 9a8aee24cf

View File

@ -44,65 +44,64 @@ def run_program(r, p):
pc += 2 pc += 2
def part_one(registers, program):
def run(r, p):
pc = 0 pc = 0
out = [] out = []
looping = True looping = True
while looping: while looping:
if pc > len(program)-1: if pc > len(p)-1:
looping = False looping = False
break break
else: else:
o, pc = run_program(registers, program) o, pc = run_program(r, p)
out.append(o) out.append(o)
print("P1: ", str(out).strip('[]').replace(" ", ""))
return out return out
def recursive_run(r, c, p):
for i in range(8):
r_copy = r.copy()
r_copy["A"] += i
out = run(r_copy, p)
if out == p:
r["A"]+=i
return True
else:
print(out,c,p)
if out == p[c-(len(p)+1):]:
r_copy = r.copy()
r_copy["A"] = (r["A"]+i)<<3
ret = recursive_run(r_copy, c-1, p)
if ret == False:
continue
else:
r["A"] = r_copy["A"]
return True
return False
def part_one(registers, program):
out = run(registers, program)
print("P1: ", str(out).strip('[]').replace(" ", ""))
def part_two(r, p): def part_two(r, p):
pc = 0
A = 0
looping = True
p_copy = p.copy() p_copy = p.copy()
p_copy.reverse() p_copy.reverse()
R = {"A": 0, "B": 0, "C": 0} R = {"A": 0, "B": 0, "C": 0}
for count, op in enumerate(p_copy): if recursive_run(R, len(p), p):
i = 0 print("P2: ", R["A"])
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) part_one(R, p)
print(p)
def main(): def main():
program = [] program = []
registers = {} registers = {}
pos = [0,0] pos = [0,0]
contents = file2list("test.txt") contents = file2list("input.txt")
for row, i in enumerate(contents): for row, i in enumerate(contents):
if "Register" in i: if "Register" in i:
a = i.split(":") a = i.split(":")