this post was submitted on 15 Dec 2023
11 points (92.3% liked)

Advent Of Code

158 readers
1 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2023

Solution Threads

M T W T F S S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS
 

Day 15: Lens Library

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ , pastebin, or github (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ


๐Ÿ”’ Thread is locked until there's at least 100 2 star entries on the global leaderboard

Edit: ๐Ÿ”“ Unlocked

you are viewing a single comment's thread
view the rest of the comments
[โ€“] [email protected] 3 points 11 months ago* (last edited 3 months ago)

Python

0.248 line-seconds (sixth simplest so far after days 6, 2, 1, 4 and 9).

import collections
import re

from .solver import Solver


def _hash(string: str) -> int:
  result = 0
  for c in string:
    result = (result + ord(c)) * 17 % 256
  return result

def _assert_full_match(pattern: str, string: str):
  m = re.fullmatch(pattern, string)
  if not m:
    raise RuntimeError(f'pattern {pattern} does not match {string}')
  return m

class Day15(Solver):
  input: list[str]

  def __init__(self):
    super().__init__(15)

  def presolve(self, input: str):
    self.input = input.rstrip().split(',')

  def solve_first_star(self) -> int:
    return sum(_hash(string) for string in self.input)

  def solve_second_star(self) -> int:
    boxes = [collections.OrderedDict() for _ in range(256)]
    for instruction in self.input:
      label, op, value = _assert_full_match(r'([a-z]+)([=-])(\d*)', instruction).groups()
      box = boxes[_hash(label)]
      match op:
        case '-':
          if label in box:
            del box[label]
        case '=':
          box[label] = value
    return sum((1 + box_idx) * (1 + lens_idx) * int(value)
                for box_idx, box in enumerate(boxes)
                for lens_idx, (_, value) in enumerate(box.items()))