Bon, j'ai sorti Numpy du coup. C'est modélisé, et assez long en fait.
# Advent of Code 2022, day 8from__future__importannotationsfrommathimportprodfromtypingimportIterable,Iterator,Set,Tuple,TypeimportnumpyasnpCoords=Tuple[int,int]classGrid:def__init__(self,matrix:np.ndarray)->None:self.matrix=matrixself.ly=matrix.shape[0]self.lx=matrix.shape[1]def__scans(self)->Iterator[Iterator[Iterator[Coords]]]:yield(((y,x)forxinrange(self.lx))foryinrange(self.ly))yield(((y,x)forxinrange(self.lx-1,-1,-1))foryinrange(self.ly))yield(((y,x)foryinrange(self.ly))forxinrange(self.lx))yield(((y,x)foryinrange(self.ly-1,-1,-1))forxinrange(self.lx))defvisible_from_outside(self)->Set[Coords]:visible_trees=set()# type: Set[Coords]forscaninself.__scans():forlineinscan:max_height=-1forcoordsinline:cur_height=self.matrix[coords]ifcur_height>max_height:visible_trees.add(coords)max_height=cur_heightreturnvisible_treesdef__viewing_distance(self,orig:Coords,line:Iterator[Coords])->int:height=self.matrix[orig]d=0forcoordsinline:d+=1ifself.matrix[coords]>=height:returndreturnddef__lines_of_sight(self,coords:Coords):y,x=coordsyield((y,x_)forx_inrange(x+1,self.lx))yield((y,x_)forx_inrange(x-1,-1,-1))yield((y_,x)fory_inrange(y+1,self.ly))yield((y_,x)fory_inrange(y-1,-1,-1))defscenic_score(self,coords:Coords):returnprod(self.__viewing_distance(coords,line)forlineinself.__lines_of_sight(coords))@classmethoddefimport_lines(class_:Type[Grid],lines:Iterable[str])->Grid:matrix=np.genfromtxt(lines,delimiter=1,autostrip=True,dtype=int)returnclass_(matrix)defsolve_both(lines:Iterable[str])->Tuple[int,int]:"""Solve both parts of today's puzzle"""# Importgrid=Grid.import_lines(lines)# Part 1visible=len(grid.visible_from_outside())# Part 2max_score=max(grid.scenic_score(coords)forcoordsinnp.ndindex(grid.matrix.shape))returnvisible,max_score
# Python avec Numpy
Posté par 🚲 Tanguy Ortolo (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.