#!/usr/bin/env python3 from sys import argv p = [] for x in open(argv[1]): x = x.strip().split() p.append((x[0], int(x[1]))) class Cpu: def __init__(self, prog): self.prog = prog self.pc = 0 self.a = 0 return def i_nop(self, arg): return def i_acc(self, arg): self.a += arg return def i_jmp(self, arg): self.pc += arg - 1 return def step(self): if self.pc >= len(self.prog): return False i = self.prog[self.pc] self.pc += 1 instr = { "nop": self.i_nop, "acc": self.i_acc, "jmp": self.i_jmp } instr[i[0]](*i[1:]) return True def halts(p): c = Cpu(p) seen = set() while True: if c.pc in seen: return (False, c.a) seen.add(c.pc) if not c.step(): return (True, c.a) print(halts(p)[1]) for i, ins in enumerate(p): n = None if ins[0] == "jmp": n = p[i] p[i] = ("nop", ins[1]) elif ins[0] == "nop": n = p[i] p[i] = ("jmp", ins[1]) else: continue a = halts(p) if a[0]: print(a[1]) break p[i] = n