aocpy/2021/d20.py

52 lines
1.5 KiB
Python

from lib import get_data
data = get_data(__file__)
for rounds in [2, 50]:
algo, img = data.strip().split("\n\n")
algo = algo.replace("\n", "")
xs = set()
img = img.splitlines()
for row in range(len(img)):
for col in range(len(img[0])):
if img[row][col] == "#":
xs.add((row, col))
for i in range(rounds):
y_min = min(v[0] for v in xs) - 6
y_max = max(v[0] for v in xs) + 6
x_min = min(v[1] for v in xs) - 6
x_max = max(v[1] for v in xs) + 6
nxs = set()
for row in range(y_min, y_max + 1):
for col in range(x_min, x_max + 1):
bin = ""
for ro in range(3):
for co in range(3):
if (row + ro, col + co) in xs:
bin += "1"
else:
bin += "0"
bin = int(bin, 2)
if algo[bin] == "#":
nxs.add((row, col))
xs = nxs
y_min_trim = y_min + 7
y_max_trim = y_max - 8
x_min_trim = x_min + 7
x_max_trim = x_max - 8
# special clean-up required because input creates pixels when there
# are no other pixels around (0b0_0000_0000)
if i % 2 == 1:
xs = [
(r, c)
for (r, c) in xs
if y_min_trim <= r <= y_max_trim and x_min_trim <= c <= x_max_trim
]
print(len(xs))