advent of code 2025

day 4 part 2

kot.pink 04e3f385 f50d2e4c

verified
Changed files
+34 -19
+34 -19
4.py
···
import sys
+
from typing import List, Optional, Tuple
-
available_rolls = 0
+
removed_rolls = 0
file = '4.input' if len(sys.argv) <= 1 else sys.argv[1]
-
grid = list(map(str.strip, open(file).readlines()))
+
grid = list(map(list, map(str.strip, open(file).readlines())))
-
def check_occupied(y: int, x: int) -> int:
+
def check_occupied(y: int, x: int) -> Optional[Tuple[int, int]]:
try:
-
return x >= 0 and y >= 0 and grid[y][x] == "@"
-
except IndexError:
-
return False
+
if x >= 0 and y >= 0 and grid[y][x] == "@":
+
return (y, x)
+
except IndexError: pass
+
return None
+
+
def compute_adj(y: int, x: int) -> List[Optional[Tuple[int, int]]]:
+
return [
+
check_occupied(y-1, x-1), check_occupied(y-1, x), check_occupied(y-1, x+1),
+
check_occupied(y, x-1), check_occupied(y, x+1),
+
check_occupied(y+1, x-1), check_occupied(y+1, x), check_occupied(y+1, x+1)
+
]
+
+
def search_removable() -> List[Tuple[int, int]]:
+
removable = []
+
for y in range(len(grid)):
+
for x in range(len(grid[y])):
+
if grid[y][x] != "@": continue
+
adj = compute_adj(y, x)
+
if sum(map(bool, adj)) < 4:
+
removable.append((y, x))
+
return removable
-
for y in range(len(grid)):
-
row = grid[y]
-
for x in range(len(row)):
-
if row[x] != "@": continue
-
adj = sum([
-
check_occupied(y-1, x-1), check_occupied(y-1, x), check_occupied(y-1, x+1),
-
check_occupied(y, x-1), check_occupied(y, x+1),
-
check_occupied(y+1, x-1), check_occupied(y+1, x), check_occupied(y+1, x+1)
-
])
-
if adj < 4:
-
available_rolls += 1
+
removable = search_removable()
+
print(f'p1: {len(removable)}')
+
+
while len(removable):
+
for (y, x) in removable:
+
grid[y][x] = "."
+
removed_rolls += 1
+
removable = search_removable()
-
print(f'p1: {available_rolls}')
-
# print(f'p2: {}')
+
print(f'p2: {removed_rolls}')