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

  • janAkali@lemmy.one
    link
    fedilink
    English
    arrow-up
    2
    ·
    edit-2
    1 year ago

    Nim

    My whole solution can be expressed in just two words: Ordered HashTable

    Total runtime: 0.068 line-seconds (40 LOC * 1.7 ms)
    Puzzle rating: exceptionally confusing description 4/10
    Code: cleaned up solution with types
    Snippet:

    proc getHash(s: string): int =
      for c in s:
        result = ((result + c.ord) * 17) mod 256
    
    proc solve(lines: seq[string]): AOCSolution[int] =
      var boxes: array[256, OrderedTable[string, int]]
      for line in lines:
        block p1:
          result.part1 += line.getHash()
    
        block p2:
          if line.endsWith('-'):
            var name = line.strip(leading=false, chars={'-'})
            boxes[getHash(name)].del(name)
          else:
            let (name, _, value) = line.partition("=")
            boxes[getHash(name)][name] = value[0].ord - '0'.ord
    
      for bi, box in boxes:
        if box.len < 1: continue
        for vi, val in enumerate(box.values):
          result.part2 += (bi+1) * (vi+1) * val