Skip to content

Commit

Permalink
Solution for day 15 (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
mkopec87 authored Dec 15, 2023
1 parent db7b537 commit ba81083
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
89 changes: 89 additions & 0 deletions src/2023/15/2024_15.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import dataclasses
import re
from typing import List

from src.utils.data import load_data
from src.utils.submission import submit_or_print


@dataclasses.dataclass
class Lens:
label: str
focal: int


@dataclasses.dataclass
class Box:
nr: int
lenses: List

def remove(self, label: str) -> None:
for lens in self.lenses:
if lens.label == label:
self.lenses.remove(lens)
break

def add(self, lens: Lens) -> None:
for i, l in enumerate(self.lenses):
if l.label == lens.label:
self.lenses.remove(l)
self.lenses.insert(i, lens)
break
else:
self.lenses.append(lens)

def power(self) -> int:
total = 0
for slot_nr, lens in enumerate(self.lenses, start=1):
total += (self.nr + 1) * slot_nr * lens.focal
return total


def main(debug: bool) -> None:
input_data = load_data(debug)

steps = input_data.strip().split(",")

# part 1
total = 0
for step in steps:
total += hash(step)
result_part1 = total

# part 2
boxes = {i: Box(i, []) for i in range(256)}
for step in steps:
match = re.match("([a-z]+)(.)(.*)", step)
label_str = match.group(1)
op_str = match.group(2)
focal_str = match.group(3)

box_nr = hash(label_str)
box = boxes[box_nr]

if op_str == "-":
box.remove(label_str)
elif op_str == "=":
box.add(Lens(label_str, int(focal_str)))

total = 0
for box in boxes.values():
total += box.power()
result_part2 = total

submit_or_print(result_part1, result_part2, debug)


def hash(string: str) -> int:
cur = 0
for ch in string:
cur += ord(ch)
cur *= 17
cur %= 256
return cur


if __name__ == "__main__":
debug_mode = True
# debug_mode = False
main(debug_mode)
1 change: 1 addition & 0 deletions src/2023/15/sample_input.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
abc=1,xxx=2,yyy=3,abc=9,abc-

0 comments on commit ba81083

Please sign in to comment.