From 9a8aee24cfd919040fa55160540e6cd24648f0a0 Mon Sep 17 00:00:00 2001 From: Daniel Weber Date: Tue, 17 Dec 2024 19:39:35 -0500 Subject: [PATCH] Finished and optimized p2 --- 2024/day17/main.py | 77 +++++++++++++++++++++++----------------------- 1 file changed, 38 insertions(+), 39 deletions(-) diff --git a/2024/day17/main.py b/2024/day17/main.py index 77dc642..5de6926 100644 --- a/2024/day17/main.py +++ b/2024/day17/main.py @@ -44,65 +44,64 @@ def run_program(r, p): pc += 2 -def part_one(registers, program): + +def run(r, p): pc = 0 out = [] looping = True while looping: - if pc > len(program)-1: + if pc > len(p)-1: looping = False break else: - o, pc = run_program(registers, program) + o, pc = run_program(r, p) out.append(o) - print("P1: ", str(out).strip('[]').replace(" ", "")) 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): - 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) + if recursive_run(R, len(p), p): + print("P2: ", R["A"]) part_one(R, p) + print(p) def main(): program = [] registers = {} pos = [0,0] - contents = file2list("test.txt") + contents = file2list("input.txt") for row, i in enumerate(contents): if "Register" in i: a = i.split(":")