Spaces:
Running
Running
File size: 1,461 Bytes
a4da721 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
def read_input(file):
with open(file, 'r') as f:
return [line.strip() for line in f.readlines()]
def count_xmas(grid):
directions = [
(0, 1), (0, -1), (1, 0), (-1, 0), # right, left, down, up
(1, 1), (1, -1), (-1, 1), (-1, -1) # diagonals: down-right, down-left, up-right, up-left
]
word = "XMAS"
count = 0
rows, cols = len(grid), len(grid[0])
for r in range(rows):
for c in range(cols):
for dr, dc in directions:
if all(0 <= r + i * dr < rows and 0 <= c + i * dc < cols and grid[r + i * dr][c + i * dc] == word[i] for i in range(len(word))):
count += 1
return count
def count_x_mas(grid):
count = 0
rows, cols = len(grid), len(grid[0])
for r in range(1, rows - 1):
for c in range(1, cols - 1):
# Check for X-MAS pattern
if (grid[r-1][c-1] == 'M' and grid[r][c-1] == 'A' and grid[r+1][c-1] == 'S' and
grid[r-1][c+1] == 'M' and grid[r][c+1] == 'A' and grid[r+1][c+1] == 'S'):
count += 1
if (grid[r-1][c+1] == 'M' and grid[r][c+1] == 'A' and grid[r+1][c+1] == 'S' and
grid[r-1][c-1] == 'M' and grid[r][c-1] == 'A' and grid[r+1][c-1] == 'S'):
count += 1
return count
file = "input.txt"
grid = read_input(file)
# Part 1
result1 = count_xmas(grid)
print(result1)
# Part 2
result2 = count_x_mas(grid)
print(result2) |