◂ 4 décembre 2024 ▸
Ceres Search : Trouver XMAS ou une croix de MAS/SAM dans une grille de lettres.
XMMAMXM …
SXSAXXX …
SXSMSMX …
⋮
- code.py
with open("input.txt", 'r', encoding='utf-8') as f:
GRID = [line[:-1] for line in f.readlines()]
WIDTH = len(GRID[0])
HEIGHT = len(GRID)
# DIRECTIONS_PART1 = [(dx,dy) for dx in range(-1,2) for dy in range(-1,2) if dx or dy]
DIRECTIONS_PART1 = ((0,1), (0,-1), (1,0), (-1,0), (1,1), (1,-1), (-1,1), (-1,-1))
DIRECTIONS_PART2 = ((1,1), (1,-1))
def get_letter(x, y):
global GRID, WIDTH, HEIGHT
return GRID[y][x] if ((0 <= x < WIDTH) and (0 <= y < HEIGHT)) else '#'
# Tests if 'MAS' in the direction (dx,dy)
def test_part1(x0, y0, dx, dy):
return [get_letter(x0 + i*dx, y0 + i*dy) for i in range(1, 4)] == list('MAS')
# Tests if 'M' and 'S' are one forward and one backward in respect to direction (dx,dy)
def test_part2(x0, y0, dx, dy):
return (get_letter(x0+dx, y0+dy) + get_letter(x0-dx, y0-dy)) in ('MS','SM')
nb1 = nb2 = 0
for x in range(0, HEIGHT):
for y in range(0, WIDTH):
if get_letter(x, y) == 'X':
nb1 += sum(1 for dir in DIRECTIONS_PART1 if test_part1(x, y, *dir))
elif get_letter(x, y) == 'A' and all(test_part2(x, y, *dir) for dir in DIRECTIONS_PART2):
nb2 += 1
print("Réponse partie 1:", nb1)
print("Réponse partie 2:", nb2)