90 lines
2.4 KiB
Python
90 lines
2.4 KiB
Python
|
#!/usr/bin/env python
|
||
|
# -*- encoding: utf-8; py-indent-offset: 4 -*-
|
||
|
|
||
|
# Author: Sebastian Mark
|
||
|
# CC-BY-SA (https://creativecommons.org/licenses/by-sa/4.0/deed.de)
|
||
|
|
||
|
# pylint: disable=missing-module-docstring,missing-function-docstring,consider-using-f-string
|
||
|
|
||
|
|
||
|
def readinput() -> list:
|
||
|
with open("input", "r", encoding="utf-8") as file:
|
||
|
lines = file.readlines()
|
||
|
return lines
|
||
|
|
||
|
|
||
|
def find_xmas(grid: list[list], x: int, y: int) -> int:
|
||
|
height = len(grid) - 1
|
||
|
width = len(grid[0]) - 1
|
||
|
|
||
|
count = 0
|
||
|
for searchstring in ["XMAS", "SAMX"]:
|
||
|
# horizontal right
|
||
|
if x + 3 <= width:
|
||
|
found = sum(grid[y][x + i] == searchstring[i] for i in range(4))
|
||
|
if found == 4:
|
||
|
count += 1
|
||
|
|
||
|
# vertical down
|
||
|
if y + 3 <= height:
|
||
|
found = sum(grid[y + i][x] == searchstring[i] for i in range(4))
|
||
|
if found == 4:
|
||
|
count += 1
|
||
|
|
||
|
# diagonal down right
|
||
|
if y + 3 <= height and x + 3 <= width:
|
||
|
found = sum(grid[y + i][x + i] == searchstring[i] for i in range(4))
|
||
|
if found == 4:
|
||
|
count += 1
|
||
|
|
||
|
# diagonal down left
|
||
|
if y + 3 <= height and x - 3 >= 0:
|
||
|
found = sum(grid[y + i][x - i] == searchstring[i] for i in range(4))
|
||
|
if found == 4:
|
||
|
count += 1
|
||
|
|
||
|
return count
|
||
|
|
||
|
|
||
|
def find_cross_mass(grid: list[list], x: int, y: int) -> int:
|
||
|
# check clockwise for
|
||
|
# M.M
|
||
|
# .A.
|
||
|
# S.S
|
||
|
# then rotate the outer ring clockwise and check again
|
||
|
for searchstring in ["MMSS", "SMMS", "SSMM", "MSSM"]:
|
||
|
found = (
|
||
|
grid[y - 1][x - 1] == searchstring[0]
|
||
|
and grid[y - 1][x + 1] == searchstring[1]
|
||
|
and grid[y + 1][x + 1] == searchstring[2]
|
||
|
and grid[y + 1][x - 1] == searchstring[3]
|
||
|
)
|
||
|
if found:
|
||
|
return 1
|
||
|
|
||
|
return 0
|
||
|
|
||
|
|
||
|
def main():
|
||
|
grid = readinput()
|
||
|
|
||
|
count = 0
|
||
|
for y, _ in enumerate(grid):
|
||
|
for x, _ in enumerate(grid[0]):
|
||
|
pos = grid[y][x]
|
||
|
if pos in ["X", "S"]:
|
||
|
count += find_xmas(grid, x, y)
|
||
|
print("XMAS count: %d" % count)
|
||
|
|
||
|
count = 0
|
||
|
for y in range(1, len(grid) - 1):
|
||
|
for x in range(1, len(grid[0]) - 1):
|
||
|
pos = grid[y][x]
|
||
|
if pos == "A":
|
||
|
count += find_cross_mass(grid, x, y)
|
||
|
print("X-MAS count: %d" % count)
|
||
|
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
main()
|