graveyard/aoc2020/8.py
2022-05-09 11:58:15 -05:00

44 lines
922 B
Python

with open("8.txt") as f:
ins = []
for line in f:
ins.append(line.strip())
def term(ins):
f = set()
f2 = set()
acc = 0
ip = 0
while True:
if ip >= len(ins):
break
i = ins[ip]
if ip in f:
if ip in f2:
return None
f2.add(ip)
f.add(ip)
# print(ip, i)
c, v = i.split(" ")
v = int(v)
if c == "acc":
acc += v
elif c == "jmp":
ip = ip + v - 1
ip += 1
return acc
for i in range(len(ins)):
l = ins[i]
if not (l.startswith("jmp") or l.startswith("nop")): continue
orig = l
if l.startswith("jmp"):
new = l.replace("jmp", "nop")
elif l.startswith("nop"):
new = l.replace("nop", "jmp")
ins[i] = new
r = term(ins)
if r is None:
ins[i] = orig
else:
print(r)
break