Published December 04, 2025
Day 4 is upon us and we have finally hit the start of the grids. When I noticed how often grids
were coming into play in AOC I made a GridBase class. This has
made my finding solutions to these types of problems so much easier. I was able to leverage that today to write my solution in ~10
minutes for both parts.
The gist of the solution is:
for direction in DIRECTIONS:
if (adj := adj + (grid.get(get_adjacent(direction, spot)) == '@')) >= MAX_ADJACENT:
break
else:
count += 1
Check each spot in the grid and see if there are no more than 4 rolls of paper adjacent. For part 2 there's logic to remove the paper as well and to run the loop as long as there are movable rolls. If you understand the types of problems that appear in AOC this is not a very difficult one.
What did come into play for me was efficiency. My initial solution took ~2 seconds to run. I've definitely had worse than that but I know
I could do better. So I went back and refactored it. I had been creating a copy of the grid and updating the removed rolls in the copy
(I leave it as an exercise to the reader why I didn't remove them in place.) Once I changed that to accumulating the coordinates of the
moved rolls and updating the existing grid after I finished processing the run time for part 2 dropped to ~450ms. That's a huge
difference. It's always useful to think about how efficient the way we work with our data is.
The full solution can be found at https://github.com/brass75/AdventOfCode/blob/main/aoc_2025/day4.py
One of my favorite things to do after solving the challenges is to refactor and optimize the solutions. After I posted this I got into a conversation with someone on Mastodon and it was pointed out that if I remove the rolls as I go (for part 2, obviously) it will need fewer iterations. How many fewer? Current run time is about a quarter of a second for part 2. Significantly better than the original 2 seconds and even the half second it was when I originally wrote this piece. The solution in GitHub reflects this change. .