advent/2020/8/solution.py

77 lines
1.7 KiB
Python
Raw Permalink Normal View History

2021-07-20 12:56:08 -05:00
#!/usr/bin/python
def uniqexists(l):
exists = {}
for i in l:
try:
exists[i] += 1
except KeyError:
exists[i] = 1
for i in exists:
if exists[i] > 1: return exists[i]
fd = open('input', 'r')
o = [i.rstrip() for i in fd.readlines()]
def sol1():
pc = 0
acc = 0
ins_hist = []
ops = o
while uniqexists(ins_hist) == None:
split = ops[pc].split(' ')
ins = split[0]
arg = split[1]
ins_hist.append(pc)
if ins == "nop":
pc += 1
elif ins == "acc":
pc += 1
acc += int(arg)
elif ins == "jmp":
if int(arg) == 0: acc += 1
pc += int(arg)
print(acc)
def sol2():
realops = o
for i in range(len(realops)):
ops = []
for j in realops:
ops.append(j)
split = ops[i].split(' ')
mod_ins = split[0]
mod_arg = split[1]
if mod_ins == "jmp":
ops[i] = "{} {}".format("nop", mod_arg)
elif mod_ins == "nop":
ops[i] = "{} {}".format("jmp", mod_arg)
pc = 0
acc = 0
ins_hist = []
try:
while uniqexists(ins_hist) == None:
split = ops[pc].split(' ')
ins = split[0]
arg = split[1]
ins_hist.append(pc)
if ins == "nop":
pc += 1
elif ins == "acc":
pc += 1
acc += int(arg)
elif ins == "jmp":
if int(arg) == 0: acc += 1
pc += int(arg)
except IndexError:
print("-!- MACHINE HALT -!-")
print(acc)
sol1()
sol2()