generated from public/aoc_template
Day 15
This commit is contained in:
parent
44e6b3e827
commit
7857f25070
71
day15.py
Normal file
71
day15.py
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
from tools.aoc import AOCDay
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
def HASH(s: str) -> int:
|
||||||
|
this_hash = 0
|
||||||
|
for c in s:
|
||||||
|
this_hash = (this_hash + ord(c)) * 17 % 256
|
||||||
|
|
||||||
|
return this_hash
|
||||||
|
|
||||||
|
|
||||||
|
class Box:
|
||||||
|
def __init__(self, nr: int):
|
||||||
|
self.nr = nr
|
||||||
|
self.labels = []
|
||||||
|
self.focal_lengths = []
|
||||||
|
|
||||||
|
def add(self, label: str, focal_length: int) -> None:
|
||||||
|
if label in self.labels:
|
||||||
|
self.focal_lengths[self.labels.index(label)] = focal_length
|
||||||
|
else:
|
||||||
|
self.labels.append(label)
|
||||||
|
self.focal_lengths.append(focal_length)
|
||||||
|
|
||||||
|
def remove(self, label: str) -> None:
|
||||||
|
if label not in self.labels:
|
||||||
|
return
|
||||||
|
|
||||||
|
p = self.labels.index(label)
|
||||||
|
self.labels.pop(p)
|
||||||
|
self.focal_lengths.pop(p)
|
||||||
|
|
||||||
|
def get_focus_power(self) -> int:
|
||||||
|
return sum((self.nr + 1) * (x + 1) * l for x, l in enumerate(self.focal_lengths))
|
||||||
|
|
||||||
|
|
||||||
|
class Day(AOCDay):
|
||||||
|
inputs = [
|
||||||
|
[
|
||||||
|
(1320, "input15_test"),
|
||||||
|
(513158, "input15"),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
(145, "input15_test"),
|
||||||
|
(200277, "input15"),
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
def part1(self) -> Any:
|
||||||
|
return sum(HASH(c) for c in self.getInput().split(","))
|
||||||
|
|
||||||
|
def part2(self) -> Any:
|
||||||
|
boxes = {}
|
||||||
|
for s in self.getInput().split(","):
|
||||||
|
if '-' in s:
|
||||||
|
label = s[:-1]
|
||||||
|
label_hash = HASH(label)
|
||||||
|
boxes.setdefault(label_hash, Box(label_hash)).remove(label)
|
||||||
|
else:
|
||||||
|
label, f_str = s.split("=")
|
||||||
|
focal_length = int(f_str)
|
||||||
|
label_hash = HASH(label)
|
||||||
|
boxes.setdefault(label_hash, Box(label_hash)).add(label, focal_length)
|
||||||
|
|
||||||
|
return sum(x.get_focus_power() for x in boxes.values())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
day = Day(2023, 15)
|
||||||
|
day.run(verbose=True)
|
||||||
1
inputs/input15
Normal file
1
inputs/input15
Normal file
File diff suppressed because one or more lines are too long
1
inputs/input15_test
Normal file
1
inputs/input15_test
Normal file
@ -0,0 +1 @@
|
|||||||
|
rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7
|
||||||
Loading…
Reference in New Issue
Block a user