Skip Navigation

šŸŽ„ - 2023 DAY 15 SOLUTIONS -šŸŽ„

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

18

You're viewing a single thread.

18 comments
  • Haskell

    Took a while to figure out what part 2 was all about. Didn't have the energy to golf this one further today, so looking forward to seeing the other solutions!

    Solution

    0.3 line-seconds

    import Data.Char
    import Data.List
    import Data.List.Split
    import qualified Data.Vector as V
    
    hash :: String -> Int
    hash = foldl' (\a c -> ((a + ord c) * 17) `rem` 256) 0
    
    hashmap :: [String] -> Int
    hashmap = focus . V.toList . foldl' step (V.replicate 256 [])
      where
        focus = sum . zipWith focusBox [1 ..]
        focusBox i = sum . zipWith (\j (_, z) -> i * j * z) [1 ..] . reverse
        step boxes s =
          let (label, op) = span isLetter s
              i = hash label
           in case op of
                ['-'] -> V.accum (flip filter) boxes [(i, (/= label) . fst)]
                ('=' : z) -> V.accum replace boxes [(i, (label, read z))]
        replace ls (n, z) =
          case findIndex ((== n) . fst) ls of
            Just j ->
              let (a, _ : b) = splitAt j ls
               in a ++ (n, z) : b
            Nothing -> (n, z) : ls
    
    main = do
      input <- splitOn "," . head . lines <$> readFile "input15"
      print $ sum . map hash $ input
      print $ hashmap input
    
18 comments