56 lines
1.2 KiB
Plaintext
56 lines
1.2 KiB
Plaintext
|
#!/usr/bin/python3
|
||
|
from pprint import pprint
|
||
|
|
||
|
prog = []
|
||
|
with open("input") as fh:
|
||
|
for ln in fh:
|
||
|
op, arg = ln.split()
|
||
|
prog.append((op, int(arg)))
|
||
|
|
||
|
class InfiniteLoopError(Exception):
|
||
|
pass
|
||
|
|
||
|
def run(prog):
|
||
|
acc = 0
|
||
|
ip = 0
|
||
|
seen = set()
|
||
|
|
||
|
while True:
|
||
|
if ip == len(prog):
|
||
|
return acc
|
||
|
if ip in seen:
|
||
|
raise InfiniteLoopError(acc)
|
||
|
seen.add(ip)
|
||
|
op = prog[ip][0]
|
||
|
arg = prog[ip][1]
|
||
|
if op == "acc":
|
||
|
acc += arg
|
||
|
ip += 1
|
||
|
elif op == "jmp":
|
||
|
ip += arg
|
||
|
elif op == "nop":
|
||
|
ip += 1
|
||
|
|
||
|
def fixprog(prog):
|
||
|
try:
|
||
|
# first try original:
|
||
|
acc = run(prog)
|
||
|
print(acc)
|
||
|
except InfiniteLoopError:
|
||
|
print("infinite loop")
|
||
|
for i in range(len(prog)):
|
||
|
op = prog[i][0]
|
||
|
if op not in ("jmp", "nop"):
|
||
|
continue
|
||
|
newop = "nop" if op == "jmp" else "jmp"
|
||
|
fixedprog = list(prog)
|
||
|
fixedprog[i] = (newop, prog[i][1])
|
||
|
print("fixed", i, fixedprog[i])
|
||
|
try:
|
||
|
acc = run(fixedprog)
|
||
|
print(acc)
|
||
|
except InfiniteLoopError:
|
||
|
print("infinite loop")
|
||
|
|
||
|
fixprog(prog)
|