summaryrefslogtreecommitdiffstats
path: root/day8/__init__.py
diff options
context:
space:
mode:
Diffstat (limited to 'day8/__init__.py')
-rw-r--r--day8/__init__.py75
1 files changed, 75 insertions, 0 deletions
diff --git a/day8/__init__.py b/day8/__init__.py
new file mode 100644
index 0000000..c6d086a
--- /dev/null
+++ b/day8/__init__.py
@@ -0,0 +1,75 @@
1from copy import copy
2from typing import Generator, Iterator, Any, List, Tuple
3
4from aoc import BaseAssignment
5
6
7class Assignment(BaseAssignment):
8 @staticmethod
9 def acc(line, accumulated_value, value):
10 return line + 1, accumulated_value + value
11
12 @staticmethod
13 def jmp(line, accumulated_value, value):
14 return line + value, accumulated_value
15
16 @staticmethod
17 def nop(line, accumulated_value, value):
18 return line + 1, accumulated_value
19
20 def read_input(self, example=False) -> List:
21 return list(super().read_input(example))
22
23 def parse_item(self, item: str) -> Tuple:
24 instruction, value = item.split(' ')
25
26 return getattr(self, instruction), int(value)
27
28 def run(self, input: List) -> int:
29 executed_lines = set()
30 accumulated_value = 0
31 line = 0
32
33 while True:
34 if line in executed_lines:
35 raise Exception(
36 f'Loop detected at line: {line}. '
37 f'Accumulated value: {accumulated_value}'
38 )
39
40 try:
41 instruction, value = input[line]
42 except IndexError:
43 break
44
45 executed_lines.add(line)
46 line, accumulated_value = instruction(
47 line, accumulated_value, value
48 )
49
50 return accumulated_value
51
52
53class AssignmentOne(Assignment):
54 pass
55
56
57class AssignmentTwo(Assignment):
58 def patch_instructions(self, input: List) -> Generator:
59 for index, (instruction, value) in enumerate(input):
60 if instruction is self.acc:
61 continue
62
63 patched_input = copy(input)
64 patched_input[index] = (
65 self.nop if instruction is self.jmp else self.jmp,
66 value
67 )
68 yield patched_input
69
70 def run(self, input: List) -> int:
71 for patched_input in self.patch_instructions(input):
72 try:
73 return super().run(patched_input)
74 except Exception:
75 continue