-
Notifications
You must be signed in to change notification settings - Fork 0
/
day24.py
109 lines (94 loc) · 3.08 KB
/
day24.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import numpy as np
def get_coords(line):
tile = [0, 0]
idx = 0
while idx < len(line):
if line[idx] == "e" or line[idx] == "w":
direction = line[idx]
idx += 1
elif line[idx] == "n" or line[idx] == "s":
direction = line[idx:idx+2]
idx += 2
if direction == "e":
tile[1] -= 2
elif direction == "w":
tile[1] += 2
else:
if direction[1] == "e":
tile[1] -= 1
elif direction[1] == "w":
tile[1] += 1
if direction[0] == "s":
tile[0] += 1
if direction[0] == "n":
tile[0] -= 1
return str(tile[0]) + "," + str(tile[1])
def get_tiles():
inp_f = open("input/day24.txt", "r")
inp = inp_f.read()
inp_list = [line for line in inp.split("\n") if line != ""]
tiles = {}
for line in inp_list:
hash_coord = get_coords(line)
if hash_coord in tiles and tiles[hash_coord]:
tiles[hash_coord] = False
else:
tiles[hash_coord] = True
return tiles
def flip_tiles(tile_arr):
new_tile_arr = tile_arr.copy()
neighbors = [(0, -2), (0, 2), (-1, -1), (-1, 1), (1, -1), (1, 1)]
for i in range(len(tile_arr)):
for j in range(len(tile_arr[i])):
count_black = 0
for neighbor in neighbors:
try:
if tile_arr[i+neighbor[0], j+neighbor[1]] == 1:
count_black += 1
except IndexError: # white neighbor
pass
if tile_arr[i, j] == 1: # black tile
if count_black == 0 or count_black > 2:
new_tile_arr[i, j] = 0
if tile_arr[i, j] == 0: # white tile
if count_black == 2:
new_tile_arr[i, j] = 1
return new_tile_arr
def part1():
tiles = get_tiles()
return sum(tiles.values())
def part2():
tiles = get_tiles()
max_x = None
min_x = None
max_y = None
min_y = None
for hash_coord in tiles:
x, y = [int(num) for num in hash_coord.split(",")]
if max_x is None or x > max_x:
max_x = x
if min_x is None or x < min_x:
min_x = x
if max_y is None or y > max_y:
max_y = y
if min_y is None or y < min_y:
min_y = y
# array of tiles, value 0 means white
arr = np.zeros((max_x - min_x + 1, max_y - min_y + 1))
for hash_coord in tiles:
if tiles[hash_coord]:
x, y = [int(num) for num in hash_coord.split(",")]
if min_x < 0:
x -= min_x
if min_y < 0:
y -= min_y
arr[x, y] = 1
num_rounds = 100
tiles_arr = np.zeros((arr.shape[0] + num_rounds * 2, arr.shape[1] + num_rounds * 2))
tiles_arr[num_rounds:-num_rounds, num_rounds:-num_rounds] = arr
for _ in range(num_rounds):
tiles_arr = flip_tiles(tiles_arr)
return np.sum(tiles_arr)
if __name__ == "__main__":
print(part1())
print(part2())