|
@@ -0,0 +1,64 @@
|
|
1
|
+import operator
|
|
2
|
+from collections import defaultdict
|
|
3
|
+from enum import Enum
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+class State(Enum):
|
|
7
|
+ clean = 0,
|
|
8
|
+ weakened = 1,
|
|
9
|
+ infected = 2,
|
|
10
|
+ flagged = 3
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+def clean_cells():
|
|
14
|
+ cells = defaultdict(lambda: State.clean)
|
|
15
|
+ for y, line in enumerate(lines):
|
|
16
|
+ for x, c in enumerate(line):
|
|
17
|
+ cells[(x, y)] = State.infected if c == '#' else State.clean
|
|
18
|
+ return cells
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+def execute(runs, transitions):
|
|
22
|
+ cells, location, direction, infected = clean_cells(), start, (0, -1), 0
|
|
23
|
+ for _ in range(runs):
|
|
24
|
+ direction = directions[cells[location]][direction]
|
|
25
|
+ cells[location] = transitions[cells[location]]
|
|
26
|
+ if cells[location] == State.infected:
|
|
27
|
+ infected += 1
|
|
28
|
+ location = tuple(map(operator.add, location, direction))
|
|
29
|
+ return infected
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+with open('data/22.txt') as file:
|
|
33
|
+ lines = file.readlines()
|
|
34
|
+ start = ((len(lines[0]) - 1) // 2, (len(lines) - 1) // 2)
|
|
35
|
+
|
|
36
|
+ right = {(0, -1): (1, 0), (1, 0): (0, 1), (0, 1): (-1, 0), (-1, 0): (0, -1)}
|
|
37
|
+ left = {v: k for k, v in right.items()}
|
|
38
|
+ identity = {v: v for v in right.values()}
|
|
39
|
+ reverse = {v: (-1 * v[0], -1 * v[1]) for v in right.values()}
|
|
40
|
+
|
|
41
|
+ directions = {
|
|
42
|
+ State.clean: left,
|
|
43
|
+ State.infected: right,
|
|
44
|
+ State.weakened: identity,
|
|
45
|
+ State.flagged: reverse
|
|
46
|
+ }
|
|
47
|
+
|
|
48
|
+ transitions = [
|
|
49
|
+ {
|
|
50
|
+ # part one
|
|
51
|
+ State.clean: State.infected,
|
|
52
|
+ State.infected: State.clean,
|
|
53
|
+ },
|
|
54
|
+ {
|
|
55
|
+ # part two
|
|
56
|
+ State.clean: State.weakened,
|
|
57
|
+ State.weakened: State.infected,
|
|
58
|
+ State.infected: State.flagged,
|
|
59
|
+ State.flagged: State.clean,
|
|
60
|
+ }
|
|
61
|
+ ]
|
|
62
|
+
|
|
63
|
+ print(f'Part one: {execute(10000, transitions[0])}')
|
|
64
|
+ print(f'Part two: {execute(10000000, transitions[1])}')
|