◂ 15 décembre 2023 ▸
Lens Library : Suivre des instructions pour placer des lentilles dans des boites et changer leur distance focale
dcf=3,hp=9,kjfhxf-,hpmvrg-,pnb=7,zxz-,vrmt=4,ghrx=7,fz-, …
- code_avec_classe.py
- code_avec_classe_hashmap.py
- code_sans_classe.py
from functools import lru_cache, reduce
Lentille = tuple[str,int]
Box = list[Lentille]
def hash(the_string: str) -> int:
return reduce(lambda h,char: (h + ord(char)) * 17 % 256, the_string, 0)
instructions = open('input.txt', 'r', encoding='utf-8').read().strip().split(',')
reponse_partie_1 = sum(map(hash, instructions))
boxes: list[Box] = [ [] for _ in range(256) ]
@lru_cache(None)
def get_box(nom: str) -> Box:
return boxes[hash(nom)]
def indice_dans_sa_box(nom: str) -> int:
for indice, (nom_i, focale) in enumerate(get_box(nom)):
if nom_i == nom:
return indice
return -1
def est_dans_sa_box(nom: str) -> bool:
return indice_dans_sa_box(nom) > -1
def enlever_de_sa_box(nom: str) -> None:
indice = indice_dans_sa_box(nom)
if indice > -1:
get_box(nom).pop(indice)
# Ou en deux lignes, mais pas optimisées du tout :
#if est_dans_sa_box(nom):
# get_box(nom).pop(index_dans_sa_box(nom))
def mettre_dans_sa_box_avec_focale(nom: str, focale: int) -> None:
box = get_box(nom)
indice = indice_dans_sa_box(nom)
if indice == -1:
box.append( (nom, focale) )
else:
box[indice] = (nom, focale)
for instruction in instructions:
if instruction.endswith('-'):
enlever_de_sa_box(instruction[:-1])
else:
nom, chiffre = instruction.split('=')
focale = int(chiffre)
mettre_dans_sa_box_avec_focale(nom, focale)
foc_power = 0
for i, box in enumerate(boxes):
for j, (nom, focale) in enumerate(box):
foc_power += (i+1) * (j+1) * focale
print("Réponse partie 1:", reponse_partie_1)
print("Réponse partie 2:", foc_power)