-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathday18.py
82 lines (60 loc) · 2.24 KB
/
day18.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
from typing import List
import matplotlib.pyplot as plt
import numpy as np
OPEN = 0
TREE = 1
LUMBER = 2
def parse_input(filename: str) -> List[str]:
lines = open(filename).read().splitlines()
return lines
def iterate(grid: np.array):
original = grid.copy()
height, width = len(grid), len(grid[0])
for y in range(height - 2):
for x in range(width - 2):
sub = original[y: y + 3, x: x + 3]
if original[y + 1][x + 1] == OPEN:
if np.count_nonzero(sub[sub == TREE]) >= 3:
grid[y + 1][x + 1] = TREE
elif original[y + 1][x + 1] == TREE:
if np.count_nonzero(sub[sub == LUMBER]) >= 3:
grid[y + 1][x + 1] = LUMBER
elif original[y + 1][x + 1] == LUMBER:
if np.count_nonzero(sub[sub == LUMBER]) >= 2 and np.count_nonzero(sub[sub == TREE]) >= 1:
grid[y + 1][x + 1] = LUMBER
else:
grid[y + 1][x + 1] = OPEN
def part1(lines: List[str]) -> int:
grid = generate_grid(lines)
for i in range(10):
iterate(grid)
return np.count_nonzero(grid[grid == 1]) * np.count_nonzero(grid[grid == 2])
def part2(lines: List[str]) -> int:
grid = generate_grid(lines)
resource_values = {}
fig, axs = plt.subplots(4, 14)
# pattern repeats from 417 to 444
for i in range(0, 473):
iterate(grid)
if 417 <= i:
axs[(i - 417) // 14, (i - 417) % 14].imshow(grid)
resource_value = np.count_nonzero(grid[grid == 1]) * np.count_nonzero(grid[grid == 2])
resource_values[i - 417] = resource_value
plt.show()
return resource_values[((1000000000 - 417 - 1) % 56)]
def generate_grid(lines: List[str]) -> np.array:
height, width = len(lines), len(lines[0])
grid = np.zeros((height + 2, width + 2))
for y, line in enumerate(lines):
for x, ch in enumerate(line):
if ch == '#':
grid[y + 1][x + 1] = LUMBER
elif ch == '|':
grid[y + 1][x + 1] = TREE
return grid
def main():
lines = parse_input('input/day18.txt')
print(f'Part 1: {part1(lines)}')
print(f'Part 2: {part2(lines)}')
if __name__ == "__main__":
main()