2020/Day 8/two.py

74 lines
1.8 KiB
Python
Raw Normal View History

2022-07-01 15:56:12 +02:00
#!/bin/python
def check(code):
visited = [False for _ in range(len(code) + 1)]
acc = 0
pointer = 0;
while not visited[pointer]:
instr = code[pointer].split(" ")
visited[pointer] = True
if instr[0] == "acc":
acc += int(instr[1])
pointer += 1
elif instr[0] == "nop":
pointer += 1
elif instr[0] == "jmp":
pointer += int(instr[1])
if pointer >= len(code):
return acc
return None
with open("input", 'r') as input:
code = [line.strip() for line in input.readlines()]
candidates = []
for idx, instr in enumerate(code):
parts = instr.split(" ")
if parts[0] == "acc":
continue
value = int(parts[1])
if parts[0] == "nop" and ((value < 2 and value > -2) or (idx + value) > len(code) + 1):
continue
candidates.append(idx)
print(len(candidates))
for candidate in candidates:
new_code = list(code)
if new_code[candidate].startswith("nop"):
new_code[candidate] = new_code[candidate].replace("nop", "jmp")
else:
new_code[candidate] = new_code[candidate].replace("jmp", "nop")
print(f"Checking candidate {candidate}...")
result = check(new_code)
if result:
print(f"Found candidate with acc: {result}")
break
# visited = [False for _ in range(len(code) + 1)]
# acc = 0
# pointer = 0;
# while not visited[pointer]:
# instr = code[pointer].split(" ")
# visited[pointer] = True
# if instr[0] == "acc":
# acc += int(instr[1])
# pointer += 1
# elif instr[0] == "nop":
# pointer += 1
# elif instr[0] == "jmp":
# pointer += int(instr[1])
# print(acc)