From ef00c627c4607ad151eb4b1651f010bf7e55a01a Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Wed, 4 Dec 2024 10:35:39 +0000 Subject: [PATCH] 2024: d04: ex1: add solution --- 2024/d04/ex1/ex1.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100755 2024/d04/ex1/ex1.py diff --git a/2024/d04/ex1/ex1.py b/2024/d04/ex1/ex1.py new file mode 100755 index 0000000..beee84b --- /dev/null +++ b/2024/d04/ex1/ex1.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python + +import itertools +import sys +from typing import NamedTuple + + +class Point(NamedTuple): + x: int + y: int + + +def solve(input: str) -> int: + def parse(input: list[str]) -> dict[Point, str]: + return { + Point(x, y): c for x, line in enumerate(input) for y, c in enumerate(line) + } + + def count_xmas(grid: dict[Point, str], dims: Point) -> int: + max_x, max_y = dims + count = 0 + for x, y in itertools.product(range(max_x), range(max_y)): + for dx, dy in itertools.product(range(-1, 1 + 1), repeat=2): + if dx == 0 and dy == 0: + continue + count += all( + grid.get(Point(x + dx * i, y + dy * i)) == c + for i, c in enumerate("XMAS") + ) + return count + + lines = input.splitlines() + grid = parse(lines) + return count_xmas(grid, Point(len(lines), len(lines[0]))) + + +def main() -> None: + input = sys.stdin.read() + print(solve(input)) + + +if __name__ == "__main__": + main()