solve day 4 part 1

This commit is contained in:
Heiko Ludwig 2024-12-04 11:35:36 +01:00
parent 80f702c12a
commit d2446e6bb8

View file

@ -7,10 +7,58 @@ def get_lines(filename: str) -> list:
return [line.strip() for line in file.readlines()] return [line.strip() for line in file.readlines()]
def main(): def get_grid(lines: list) -> list:
lines = get_lines("sample-input.txt") grid = []
# lines = get_lines("input.txt") for line in lines:
row = []
for char in line:
row.append(char)
grid.append(row)
return grid
def check_xmas_from_pos(grid: list, row: int, col: int,
direction: tuple, xmas_letters: list) -> bool:
if grid[row][col] != xmas_letters[0]:
# wrong letter, end of recursion
return False
if len(xmas_letters) == 1:
# found the last letter, end of recursion
return True
# out of bounds, end of recursion
new_row = row + direction[0]
new_col = col + direction[1]
if new_row < 0 or new_row >= len(grid):
return False
if new_col < 0 or new_col >= len(grid[0]):
return False
# go deeper into recursion with one less letter on the search string
return check_xmas_from_pos(grid, new_row, new_col, direction, xmas_letters[1:])
def get_xmas_appearances(grid: list) -> int:
xmas_appearances = 0
directions = [(0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1)]
xmas_letters = ['X', 'M', 'A', 'S']
for row in range(len(grid)):
for col in range(len(grid[0])):
for direction in directions:
if check_xmas_from_pos(grid, row, col, direction, xmas_letters):
print(f"Found XMAS at position ({row}, {col}) in direction {direction}")
xmas_appearances += 1
return xmas_appearances
def main():
# lines = get_lines("sample-input.txt")
lines = get_lines("input.txt")
grid = get_grid(lines)
xmas_appearances = get_xmas_appearances(grid)
print(f"Part 1: The word XMAS appears {xmas_appearances} times.")
if __name__ == '__main__': if __name__ == '__main__':
main() main()