• # Python avec Numpy

    Posté par (site web personnel) . En réponse au message Avent du Code, jour 8. Évalué à 4.

    Bon, j'ai sorti Numpy du coup. C'est modélisé, et assez long en fait.

    # Advent of Code 2022, day 8
    from __future__ import annotations
    from math import prod
    from typing import Iterable, Iterator, Set, Tuple, Type
    import numpy as np
    Coords = Tuple[int, int]
    class Grid:
     def __init__(self, matrix: np.ndarray) -> None:
     self.matrix = matrix
     self.ly = matrix.shape[0]
     self.lx = matrix.shape[1]
     def __scans(self) -> Iterator[Iterator[Iterator[Coords]]]:
     yield (((y, x) for x in range(self.lx)) for y in range(self.ly))
     yield (((y, x) for x in range(self.lx - 1, -1, -1))
     for y in range(self.ly))
     yield (((y, x) for y in range(self.ly)) for x in range(self.lx))
     yield (((y, x) for y in range(self.ly - 1, -1, -1))
     for x in range(self.lx))
     def visible_from_outside(self) -> Set[Coords]:
     visible_trees = set() # type: Set[Coords]
     for scan in self.__scans():
     for line in scan:
     max_height = -1
     for coords in line:
     cur_height = self.matrix[coords]
     if cur_height > max_height:
     visible_trees.add(coords)
     max_height = cur_height
     return visible_trees
     def __viewing_distance(self, orig: Coords, line: Iterator[Coords]) -> int:
     height = self.matrix[orig]
     d = 0
     for coords in line:
     d += 1
     if self.matrix[coords] >= height:
     return d
     return d
     def __lines_of_sight(self, coords: Coords):
     y, x = coords
     yield ((y, x_) for x_ in range(x + 1, self.lx))
     yield ((y, x_) for x_ in range(x - 1, -1, -1))
     yield ((y_, x) for y_ in range(y + 1, self.ly))
     yield ((y_, x) for y_ in range(y - 1, -1, -1))
     def scenic_score(self, coords: Coords):
     return prod(self.__viewing_distance(coords, line)
     for line in self.__lines_of_sight(coords))
     @classmethod
     def import_lines(class_: Type[Grid], lines: Iterable[str]) -> Grid:
     matrix = np.genfromtxt(lines, delimiter=1, autostrip=True, dtype=int)
     return class_(matrix)
    def solve_both(lines: Iterable[str]) -> Tuple[int, int]:
     """Solve both parts of today's puzzle"""
     # Import
     grid = Grid.import_lines(lines)
     # Part 1
     visible = len(grid.visible_from_outside())
     # Part 2
     max_score = max(grid.scenic_score(coords) for coords
     in np.ndindex(grid.matrix.shape))
     return visible, max_score