fromcollections.abcimportIterablefromtypingimportOptional,SelffromenumimportEnumimportioimportaocCoords=tuple[int,int]classTerrain(Enum):ASH='.'ROCK='#'def__str__(self)->str:ifselfisself.ASH:return' 'ifselfisself.ROCK:return'▒'raiseValueError('invalid terrain value')classPattern:def__init__(self,array:Iterable[Iterable[Terrain]]):self.matrix=list(list(line)forlineinarray)self.ly=len(self.matrix)self.lx=len(self.matrix[0])@classmethoddefimport_lines(cls,lines:Iterable[str])->Self:returncls((Terrain(char)forcharinline.rstrip())forlineinlines)def__getitem__(self,coords:Coords)->Terrain:y,x=coordsreturnself.matrix[y][x]def__str__(self)->str:s=io.StringIO()forlineinself.matrix:forterraininline:s.write(str(terrain))s.write('\n')returns.getvalue()defy_reflection_errors(self,y:int)->int:"""Count the number of errors in a horizontal reflection between y - 1 and y. Return 0, 1 or 2 (meaning many)."""errors=0foriinrange(min(y,self.ly-y)):y1=y-1-iy2=y+iforxinrange(self.lx):errors+=self[y1,x]!=self[y2,x]iferrors>=2:returnerrorsreturnerrorsdefx_reflection_errors(self,x:int)->int:"""Count the number of errors in a vertical reflection between x - 1 and x. Return 0, 1 or 2 (meaning many)."""errors=0foriinrange(min(x,self.lx-x)):x1=x-1-ix2=x+iforyinrange(self.ly):errors+=self[y,x1]!=self[y,x2]iferrors>=2:returnerrorsreturnerrorsdefy_reflection1(self)->Optional[int]:foryinrange(1,self.ly):ifself.y_reflection_errors(y)==0:returnyreturnNonedefx_reflection1(self)->Optional[int]:forxinrange(1,self.lx):ifself.x_reflection_errors(x)==0:returnxreturnNonedefy_reflection2(self)->Optional[int]:foryinrange(1,self.ly):ifself.y_reflection_errors(y)==1:returnyreturnNonedefx_reflection2(self)->Optional[int]:forxinrange(1,self.lx):ifself.x_reflection_errors(x)==1:returnxreturnNonedefpart1(lines:aoc.Data)->int:"""Solve puzzle part 1: determine the sum of perfect reflection columns and×ばつ that of perfect reflection lines."""total=0fori,groupinenumerate(aoc.group_lines(lines)):pattern=Pattern.import_lines(group)if(x:=pattern.x_reflection1())isnotNone:total+=xelif(y:=pattern.y_reflection1())isnotNone:total+=100*yelse:raiseValueError('pattern without reflection‽')returntotaldefpart2(lines:aoc.Data)->int:"""Solve puzzle part 1: determine the sum of imperfect reflection columns and ×ばつ that of imperfect reflection lines."""total=0fori,groupinenumerate(aoc.group_lines(lines)):pattern=Pattern.import_lines(group)if(x:=pattern.x_reflection2())isnotNone:total+=xelif(y:=pattern.y_reflection2())isnotNone:total+=100*yelse:raiseValueError('pattern without reflection‽')returntotal
[^] # Re: Pas bien compliqué... en reformulant
Posté par 🚲 Tanguy Ortolo (site web personnel) . En réponse au message Advent of Code, jour 13. Évalué à 3.
Allez, voici le code :