day 4
This commit is contained in:
94
2025/04/solution.py
Executable file
94
2025/04/solution.py
Executable file
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
import pathlib
|
||||
|
||||
def read_input():
|
||||
path = pathlib.Path(sys.argv[1]) if len(sys.argv) > 1 else pathlib.Path("input.txt")
|
||||
return path.read_text().rstrip("\n")
|
||||
|
||||
def parse(data):
|
||||
return data.splitlines()
|
||||
|
||||
def part1(data):
|
||||
total = 0
|
||||
|
||||
def surround(arr, x, y):
|
||||
s = 0
|
||||
def has(k, h):
|
||||
nx = x + k
|
||||
ny = y + h
|
||||
if nx < 0 or nx >= len(arr):
|
||||
return 0
|
||||
if ny < 0 or ny >= len(arr[0]):
|
||||
return 0
|
||||
if arr[nx][ny] == '@':
|
||||
return 1
|
||||
return 0
|
||||
s += has(-1, -1)
|
||||
s += has(-1, 0)
|
||||
s += has(-1, 1)
|
||||
s += has(0, -1)
|
||||
s += has(0, 1)
|
||||
s += has(1, -1)
|
||||
s += has(1, 0)
|
||||
s += has(1, 1)
|
||||
return s
|
||||
|
||||
for i in range(len(data)):
|
||||
for j in range(len(data[0])):
|
||||
if data[i][j] == '@':
|
||||
cnt = surround(data, i, j)
|
||||
if cnt < 4:
|
||||
total += 1
|
||||
return total
|
||||
|
||||
def part2(data):
|
||||
total = 0
|
||||
|
||||
cpy = [list(row) for row in data]
|
||||
|
||||
def surround(arr, x, y):
|
||||
s = 0
|
||||
def has(k, h):
|
||||
nx = x + k
|
||||
ny = y + h
|
||||
if nx < 0 or nx >= len(arr):
|
||||
return 0
|
||||
if ny < 0 or ny >= len(arr[0]):
|
||||
return 0
|
||||
if arr[nx][ny] == '@':
|
||||
return 1
|
||||
return 0
|
||||
s += has(-1, -1)
|
||||
s += has(-1, 0)
|
||||
s += has(-1, 1)
|
||||
s += has(0, -1)
|
||||
s += has(0, 1)
|
||||
s += has(1, -1)
|
||||
s += has(1, 0)
|
||||
s += has(1, 1)
|
||||
return s
|
||||
|
||||
old = -1
|
||||
|
||||
while old != total:
|
||||
old = total
|
||||
for i in range(len(cpy)):
|
||||
for j in range(len(cpy[0])):
|
||||
if cpy[i][j] == '@':
|
||||
cnt = surround(cpy, i, j)
|
||||
if cnt < 4:
|
||||
cpy[i][j] = "x"
|
||||
total += 1
|
||||
return total
|
||||
|
||||
def main():
|
||||
raw = read_input()
|
||||
data = parse(raw)
|
||||
r1 = part1(data)
|
||||
r2 = part2(data)
|
||||
print(r1)
|
||||
print(r2)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user