def parse_input(filename): with open(filename, "r") as f: lines = f.readlines() registers = {} for line in lines: if line.startswith("Register"): reg, val = line.split(":") registers[reg.split()[1]] = int(val.strip()) elif line.startswith("Program"): program = list(map(int, line.split(":")[1].strip().split(","))) return registers, program def run_program(registers, program): output = [] ip = 0 while 0 <= ip < len(program): opcode = program[ip] operand = program[ip + 1] if opcode == 0: # adv denominator = 2 ** (operand if operand < 4 else registers["ABC"[operand - 4]]) registers["A"] //= denominator elif opcode == 1: # bxl registers["B"] ^= operand elif opcode == 2: # bst registers["B"] = operand % 8 elif opcode == 3: # jnz if registers["A"] != 0: ip = operand continue elif opcode == 4: # bxc registers["B"] ^= registers["C"] elif opcode == 5: # out val = (operand if operand < 4 else registers["ABC"[operand - 4]]) % 8 output.append(str(val)) elif opcode == 6: # bdv denominator = 2 ** (operand if operand < 4 else registers["ABC"[operand - 4]]) registers["B"] //= denominator elif opcode == 7: # cdv denominator = 2 ** (operand if operand < 4 else registers["ABC"[operand - 4]]) registers["C"] //= denominator ip += 2 return ",".join(output) registers, program = parse_input("./input.txt") print(run_program(registers.copy(), program)) for a in range(1, 1000000): # Adjust range if needed registers["A"] = a registers["B"] = 0 registers["C"] = 0 output = run_program(registers.copy(), program) if output == ",".join(map(str, program)): print(a) break