]> git.sommitrealweird.co.uk Git - advent-of-code-2020.git/blob - day08/computer.py
Day 12
[advent-of-code-2020.git] / day08 / computer.py
1 #!/usr/bin/python3
2
3 class Computer:
4
5     def __init__(self, instructions=[], break_on_exec=0):
6         self.__acc__=0
7         self.__pos__=0
8         self.__instructions__=instructions
9         self.__executed_count__={}
10         self.__keep_running__=True
11         self.__break_on_exec_number__=break_on_exec
12         self.__exited_on_break__=False
13
14     def set_instructions(self, instructions):
15         self.__instructions__=instructions
16
17     def run(self):
18         while self.keep_running():
19             self.run_command()
20         # when we're done, return the accumulator
21         return self.__acc__
22
23     def keep_running(self):
24         if self.__pos__ >= len(self.__instructions__):
25             self.__keep_running__=False
26         return self.__keep_running__
27
28     def exited_on_break(self):
29         return self.__exited_on_break__
30
31     def run_command(self):
32         if self.__pos__ in self.__executed_count__:
33             self.__executed_count__[self.__pos__]+=1
34         else:
35             self.__executed_count__[self.__pos__]=1
36
37         if self.__break_on_exec_number__ > 0 and self.__executed_count__[self.__pos__] >= self.__break_on_exec_number__:
38             self.__keep_running__=False
39             self.__exited_on_break__=True
40             return
41         else:
42             (instruction,param) = self.__instructions__[self.__pos__]
43             if instruction == "nop":
44                 # do nothing, except increment the program counter
45                 self.__pos__+=1
46             elif instruction == "acc":
47                 val=int(param)
48                 self.__acc__+=val
49                 self.__pos__+=1
50             elif instruction == "jmp":
51                 val=int(param)
52                 self.__pos__+=val
53             else:
54                 raise Exception("WTAF - that's not a real instruction!")
55         return
56
57 def main():
58     instructions = [line.rstrip().split(" ") for line in open("input.txt", "r")]
59     comp = Computer(instructions, break_on_exec=2)
60
61     print("Acc was {} when computer finished.".format(comp.run()))
62
63 if __name__ == "__main__":
64     main()