Day 24
This commit is contained in:
51
day24/part2.py
Normal file
51
day24/part2.py
Normal file
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
import numpy as np
|
||||
from scipy.signal import convolve
|
||||
|
||||
lines = (x.strip() for x in open("input.txt"))
|
||||
|
||||
blacks = set()
|
||||
|
||||
for line in lines:
|
||||
x, y = 0, 0
|
||||
while len(line):
|
||||
if line[0] == "n":
|
||||
y += 1
|
||||
x += 1 if line[1] == "e" else 0
|
||||
line = line[2:]
|
||||
elif line[0] == "s":
|
||||
y -= 1
|
||||
x -= 1 if line[1] == "w" else 0
|
||||
line = line[2:]
|
||||
else:
|
||||
x += 1 if line[0] == "e" else -1
|
||||
line = line[1:]
|
||||
if (x, y) in blacks:
|
||||
blacks.discard((x, y))
|
||||
else:
|
||||
blacks.add((x, y))
|
||||
|
||||
|
||||
x = np.array(list([x, y] for x, y in blacks)).T
|
||||
lower = np.min(x, axis=1)
|
||||
upper = np.max(x, axis=1)
|
||||
grid = np.zeros((upper[0]-lower[0]+1, upper[1]-lower[1]+1))
|
||||
x -= np.array([lower]).T
|
||||
grid[x[0], x[1]] = 1
|
||||
kernel = np.array([
|
||||
[1, 1, 0],
|
||||
[1, 0, 1],
|
||||
[0, 1, 1]
|
||||
])
|
||||
|
||||
for _ in range(100):
|
||||
grid = np.pad(grid, pad_width=1)
|
||||
neighbors = convolve(grid, kernel, mode='same', method="direct")
|
||||
set_inactive = np.logical_and(grid == 1, np.logical_or(neighbors == 0, neighbors > 2))
|
||||
set_active = np.logical_and(grid == 0, neighbors == 2)
|
||||
grid[set_inactive] = 0
|
||||
grid[set_active] = 1
|
||||
a = tuple(slice(np.min(idxs), np.max(idxs)+1) for idxs in np.where(grid == 1))
|
||||
grid = grid[a]
|
||||
|
||||
print(np.sum(grid))
|
||||
Reference in New Issue
Block a user