Day 4: Part 2

This commit is contained in:
2025-12-05 07:04:03 +01:00
parent 5057e2e8eb
commit 3ce348ebf6

View File

@@ -1,5 +1,5 @@
with open("day4/input.txt") as file:
paperrolls = [str(line.strip("\n")) for line in file.readlines()]
paperrolls = [list(line.strip("\n")) for line in file.readlines()]
h = len(paperrolls)
@@ -7,18 +7,32 @@ w = len(paperrolls[0]) if h>0 else 0
dirs = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]
def neighbors_count(r,c):
def neighbor_count(g, r, c):
cnt = 0
for dr,dc in dirs:
rr,cc = r+dr, c+dc
if 0 <= rr < h and 0 <= cc < w and paperrolls[rr][cc] == '@':
for dr, dc in dirs:
rr, cc = r+dr, c+dc
if 0 <= rr < h and 0 <= cc < w and g[rr][cc] == '@':
cnt += 1
return cnt
accessible = 0
for r in range(h):
for c in range(w):
if paperrolls[r][c] == '@' and neighbors_count(r,c) < 4:
accessible += 1
# total rolls
total = sum(row.count('@') for row in paperrolls)
print(accessible)
# compute 4-core complement by iterative simultaneous removal
g = [row[:] for row in paperrolls]
removed = 0
while True:
to_remove = []
for r in range(h):
for c in range(w):
if g[r][c] == '@' and neighbor_count(g, r, c) < 4:
to_remove.append((r,c))
if not to_remove:
break
removed += len(to_remove)
for r,c in to_remove:
g[r][c] = '.'
print("Total rolls:", total)
print("Removable (eventually):", removed)
print("Remaining in 4-core:", total - removed)