Day 8 2020
[advent-of-code-2020.git] / day08 / part2.py
1 #!/usr/bin/python
2
3 import computer
4 import copy
5
6 def get_possible_change_locations(instructions):
7     change_locations=[]
8     instruction_location=0
9     for instruction,param in instructions:
10         if instruction == "nop":
11             change_locations.append(instruction_location)
12         elif instruction == "jmp":
13             change_locations.append(instruction_location)
14         instruction_location+=1
15     return change_locations
16
17 def main():
18     # read the instructions
19     instructions=[line.rstrip().split(" ") for line in open("input.txt", "r")]
20     possible_change_locations=get_possible_change_locations(instructions)
21
22     for change_location in possible_change_locations:
23         new_instructions=copy.deepcopy(instructions)
24         instruction = new_instructions[change_location][0]
25         param = new_instructions[change_location][1]
26         if instruction == "nop":
27             instruction = "jmp"
28         else:
29             instruction = "nop"
30
31         new_instructions[change_location][0]=instruction
32
33         comp=computer.Computer(new_instructions,break_on_exec=10)
34         acc=comp.run()
35         if comp.exited_on_break():
36             continue
37         else:
38             print ("Replaced instruction at pos: {}, computer terminated normally with acc: {}".format(change_location, acc))
39             break
40
41 if __name__ == "__main__":
42     main()