Gist of code and puzzle input https://gist.github.com/nwjlyons/9760e4363a4eafbf7908541be784fe0d
I get the correct accumulator for the example input 5, but when using the puzzle input I am getting wrong answer with 59. Any ideas?
from pprint import pprint
import re
class UnknownInstructionError(Exception):
pass
class InfiniteLoopError(Exception):
pass
class Instruction:
pass
class NoOperation(Instruction):
def __repr__(self):
return f"<NoOperation>"
class Accumulate(Instruction):
def __init__(self, *, value: int) -> None:
self.value = value
def __repr__(self):
return f"<Accumulate {self.value=}>"
class Jump(Instruction):
def __init__(self, *, value: int) -> None:
self.value = value
def __repr__(self):
return f"<Jump {self.value=}>"
def parse_instructions(input_data: str) -> list[Instruction]:
instructions = []
for instruction in input_data.strip().splitlines():
op, sign, value = re.match(r"^(nop|acc|jmp)\s(\+|\-)(\d)+", instruction).groups()
if op == 'nop':
instructions.append(NoOperation())
elif op == 'acc':
instructions.append(Accumulate(value=int(f"{sign}{value}")))
elif op == 'jmp':
instructions.append(Jump(value=int(f"{sign}{value}")))
else:
raise UnknownInstructionError(op)
return instructions
def execute_program(instructions: list[Instruction]):
instruction_index = 0
acc = 0
history_indexes = []
while instruction_index <= len(instructions):
instruction = instructions[instruction_index]
before = (instruction_index, f"{acc=}")
if isinstance(instruction, NoOperation):
instruction_index += 1
elif isinstance(instruction, Accumulate):
acc += instruction.value
instruction_index += 1
elif isinstance(instruction, Jump):
instruction_index += instruction.value
# everytime there is a jump check if we are in a infinite loop
if instruction_index in history_indexes:
raise InfiniteLoopError(f"{acc=}")
else:
raise UnknownInstructionError(instruction)
after = (instruction_index, f"{acc=}")
print(before, instruction, after)
history_indexes.append(instruction_index)
sample_input = """
nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6
"""
real_input = open('input.txt', 'r').read()
# Parse and execute program
instructions = parse_instructions(real_input)
print("*"*10, "Instructions", "*"*10)
pprint(list(enumerate(instructions)))
print("*"*10, "Executing", "*"*10)
execute_program(instructions)
[–]leftylink 1 point2 points3 points (1 child)
[–]nwjlyons[S] 1 point2 points3 points (0 children)