69 lines
1.5 KiB
Python
69 lines
1.5 KiB
Python
|
def read_file():
|
||
|
with open("input.txt","r") as f:
|
||
|
return f.read().split('\n')
|
||
|
|
||
|
def process(instructions):
|
||
|
acc = 0
|
||
|
i = 0
|
||
|
visited = []
|
||
|
while True:
|
||
|
if i not in range(len(instructions)):
|
||
|
# we've terminated bois
|
||
|
return acc, False
|
||
|
if i in visited:
|
||
|
# it loops
|
||
|
return acc, True
|
||
|
visited.append(i)
|
||
|
instruction = instructions[i]
|
||
|
operation = instruction[:3]
|
||
|
argument = instruction[4:]
|
||
|
if operation == "nop":
|
||
|
i += 1
|
||
|
elif operation == "acc":
|
||
|
acc += int(argument)
|
||
|
i += 1
|
||
|
elif operation == "jmp":
|
||
|
i += int(argument)
|
||
|
|
||
|
def part1(instructions):
|
||
|
acc, repeats = process(instructions)
|
||
|
return acc
|
||
|
|
||
|
def terminates(instructions):
|
||
|
if process(instructions):
|
||
|
return False
|
||
|
return True
|
||
|
|
||
|
def part2(instructions):
|
||
|
acc = 0
|
||
|
i = 0
|
||
|
visited = []
|
||
|
while True:
|
||
|
if i in visited:
|
||
|
for i in reversed(visited):
|
||
|
new_instructions = [instruction for instruction in instructions]
|
||
|
if instructions[i][:3] == "jmp":
|
||
|
new_instructions[i] = instructions[i].replace("jmp","nop")
|
||
|
elif instructions[i][:3] == "nop":
|
||
|
new_instructions[i] = instructions[i].replace("nop","jmp")
|
||
|
new_acc, repeats = process(new_instructions)
|
||
|
if not repeats:
|
||
|
return new_acc
|
||
|
visited.append(i)
|
||
|
instruction = instructions[i]
|
||
|
operation = instruction[:3]
|
||
|
argument = instruction[4:]
|
||
|
if operation == "nop":
|
||
|
i += 1
|
||
|
elif operation == "acc":
|
||
|
acc += int(argument)
|
||
|
i += 1
|
||
|
elif operation == "jmp":
|
||
|
i += int(argument)
|
||
|
|
||
|
def main():
|
||
|
instructions = read_file()
|
||
|
print(part1(instructions), part2(instructions))
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
main()
|