aoc24/day4/solution2.py
2024-12-04 16:04:03 +01:00

45 lines
1.3 KiB
Python

def read_grid(filename):
grid = []
with open(filename, 'r') as file:
for line in file:
grid.append(list(line.strip()))
return grid
# Function to check if a diagonal forms 'MAS' or 'SAM'
def check_diagonal(grid, x, y, dx, dy):
rows = len(grid)
cols = len(grid[0])
letters = []
for k in range(-1, 2): # Positions: -1, 0, 1
nx = x + dx * k
ny = y + dy * k
if 0 <= nx < rows and 0 <= ny < cols:
letters.append(grid[nx][ny])
else:
return False # Out of bounds
word = ''.join(letters)
return word == 'MAS' or word == 'SAM'
def count_xmas_patterns(grid):
rows = len(grid)
cols = len(grid[0])
count = 0
for x in range(1, rows - 1):
for y in range(1, cols - 1):
if grid[x][y] != 'A':
continue
diagonal1 = check_diagonal(grid, x, y, -1, -1) # Top-left to bottom-right
diagonal2 = check_diagonal(grid, x, y, -1, 1) # Top-right to bottom-left
if diagonal1 and diagonal2:
count += 1
return count
# Main execution
if __name__ == "__main__":
grid = read_grid('input.txt')
# grid = read_grid('example.txt')
total_xmas = count_xmas_patterns(grid)
print(total_xmas)