aoc2025/vicky/dec4/dec4.py

113 lines
2.5 KiB
Python

#!/usr/bin/env python
# coding: utf-8
# # Puzzle 2 of AoC 2025
# Author: Victoria Ramírez López
#
# Date: Dec 4, 2025
# In[23]:
import numpy as np
from scipy.signal import convolve2d
# In[110]:
# Read input file
paper_roll_grid = open('paper_roll_grid.txt', mode ='r') # Open in 'read only' mode
grid = paper_roll_grid.readlines()
grid = [line.strip('\n') for line in grid]
# In[111]:
# Find roll papers accessible by fork lift
total_accessible_rolls = 1
total_removed_rolls = 0
# Turn grid to boolean matrix
bool_grid = create_boolean_grid(grid)
bool_grid_np = np.array(bool_grid) # Convert into numpy array
# For part 1
accessible_rolls = find_accessible_rolls(bool_grid_np)
total_accessible_rolls = accessible_rolls.sum()
print('Part 1 answer: ', total_accessible_rolls)
# For part 2
while total_accessible_rolls >= 1:
accessible_rolls = find_accessible_rolls(bool_grid_np)
total_accessible_rolls = accessible_rolls.sum()
bool_grid_np = remove_accessible_rolls(bool_grid_np,accessible_rolls)
total_removed_rolls = total_removed_rolls + total_accessible_rolls
print('Part 2 answer:', total_removed_rolls)
# In[98]:
def find_accessible_rolls(bool_grid_np):
# This function finds the number of rolls that can be
# accessed by forklift
# input: grid = [[String]]
# output: sum_accessible_rolls = int
# Add padding
bool_grid_padded = np.pad(bool_grid_np, 1, mode='constant')
# Calculate how many rolls surround each roll
convolution = convolve2d(bool_grid_padded,
[[1,1,1],[1,0,1],[1,1,1]], mode='same')
convolution = convolution[1:-1,1:-1] # Remove padding
# Determine how many rolls are reachable
accessible_rolls = bool_grid_np & (convolution < 4)
return accessible_rolls
# In[109]:
def remove_accessible_rolls(bool_grid_np, accessible_rolls):
# This function removes the number of rolls that can be
# accessed by forklift
# input: accessible_rolls = numpy array
# output: updated_grid = numpy array
updated_grid = np.logical_not(accessible_rolls) & bool_grid_np
return(updated_grid)
# In[112]:
def create_boolean_grid(grid):
# This function turns the original grid to a matrix where
# '@' is 1 and '.' is 0
# input: grid = [String]
# output: boolean_grid = [int]
boolean_grid = []
for row in grid:
boolean_row = [1 if x == '@' else 0 for x in row]
boolean_grid.append(boolean_row)
return boolean_grid
# In[ ]: