From 7d160342d96c6185b685b811fe4a8fa9959ae9ad Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Thu, 8 Dec 2022 08:19:28 +0100 Subject: [PATCH] 2022: d08: ex2: add solution --- 2022/d08/ex2/ex2.py | 60 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100755 2022/d08/ex2/ex2.py diff --git a/2022/d08/ex2/ex2.py b/2022/d08/ex2/ex2.py new file mode 100755 index 0000000..ed6d9b4 --- /dev/null +++ b/2022/d08/ex2/ex2.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python + +import dataclasses +import sys +from collections.abc import Iterator + + +@dataclasses.dataclass +class Point: + x: int + y: int + + +def solve(input: list[list[int]]) -> int: + def up(p: Point) -> Iterator[Point]: + x = p.x + while (x := x - 1) >= 0: + yield Point(x, p.y) + + def down(p: Point) -> Iterator[Point]: + x = p.x + while (x := x + 1) < len(input): + yield Point(x, p.y) + + def left(p: Point) -> Iterator[Point]: + y = p.y + while (y := y - 1) >= 0: + yield Point(p.x, y) + + def right(p: Point) -> Iterator[Point]: + y = p.y + while (y := y + 1) < len(input[0]): + yield Point(p.x, y) + + def visible_trees(p: Point, neighbours: Iterator[Point]) -> Iterator[Point]: + height = input[p.x][p.y] + for n in neighbours: + yield n + if height <= input[n.x][n.y]: + break + + def score(p: Point) -> int: + score = 1 + for neighbours in (up, down, left, right): + score *= len(list(visible_trees(p, neighbours(p)))) + return score + + scores = [ + [score(Point(x, y)) for y in range(len(input[x]))] for x in range(len(input)) + ] + return max(map(max, scores)) + + +def main() -> None: + input = [[int(c) for c in line] for line in sys.stdin.read().splitlines()] + print(solve(input)) + + +if __name__ == "__main__": + main()