Day 4 - Advent of Code 2025
Working solutions for the day 4 puzzles.
Part One
""" day_04_01.py """
# usage: python3 day_04_01.py
def get(filename):
""" contents of filename """
with open(filename, 'r', encoding='utf-8') as infile:
data = infile.read().strip()
return data
def test(data, given_solution):
""" testing """
assert solve(data) == given_solution
def access(pos, xs, grid):
""" less than 4 neighbours """
deltas = [(0, -1), (0, 1), (-1, 0), (1, 0),
(-1, -1), (1, 1), (1, -1), (-1, 1)]
count = 0
y, x = divmod(pos, xs)
for dx, dy in deltas:
i = x + dx + (y + dy) * xs
if grid.get(i, '.') == '@':
count += 1
return count < 4
def solve(data):
""" solve the puzzle """
rolls = {i: symbol for i, symbol in enumerate(data) if symbol == '@'}
cols = data.find('\n') + 1
return sum(1 for i in rolls if access(i, cols, rolls))
if __name__ == '__main__':
test(get('example01'), 13)
puzzle = get('input')
solution = solve(puzzle)
print(solution)
Part Two
""" day_04_02.py """
# usage: python3 day_04_02.py
def get(filename):
""" contents of filename """
with open(filename, 'r', encoding='utf-8') as infile:
data = infile.read().strip()
return data
def test(data, given_solution):
""" testing """
assert solve(data) == given_solution
def access(pos, xs, grid):
""" less than 4 neighbours """
deltas = [(0, -1), (0, 1), (-1, 0), (1, 0),
(-1, -1), (1, 1), (1, -1), (-1, 1)]
count = 0
y, x = divmod(pos, xs)
for dx, dy in deltas:
i = x + dx + (y + dy) * xs
if grid.get(i, '.') == '@':
count += 1
return count < 4
def remove_access(xs, grid):
""" remove rolls with access """
return {i: 'x' if access(i, xs, grid) else symbol
for i, symbol in grid.items()}
def tally(item, grid):
""" how many items """
return list(grid.values()).count(item)
def solve(data):
""" solve the puzzle """
rolls = {i: symbol for i, symbol in enumerate(data) if symbol == '@'}
cols = data.find('\n') + 1
before, after = -1, -2
while before != after:
before = after
rolls = remove_access(cols, rolls)
after = tally('x', rolls)
return after
if __name__ == '__main__':
test(get('example01'), 43)
puzzle = get('input')
solution = solve(puzzle)
print(solution)
