Day 3: Lobby

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)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

  • Amy@piefed.blahaj.zone
    link
    fedilink
    English
    arrow-up
    4
    ·
    1 month ago

    Haskell

    Yay, dynamic programming!

    import Data.Map qualified as Map  
    
    maxJolt :: Int -> [Char] -> Int  
    maxJolt r xs = read $ maximize r 0  
      where  
        n = length xs  
        maximize =  
          (curry . (Map.!) . Map.fromList . (zip <*> map (uncurry go)))  
            [(k, o) | k <- [1 .. r], o <- [r - k .. n - k]]  
        go k o =  
          maximum $ do  
            (x, o') <- drop o $ zip xs [1 .. n - (k - 1)]  
            return . (x :) $ if k == 1 then [] else maximize (k - 1) o'  
    
    main = do  
      input <- lines <$> readFile "input03"  
      mapM_ (print . sum . (`map` input) . maxJolt) [2, 12]  
    
    • Amy@piefed.blahaj.zone
      link
      fedilink
      English
      arrow-up
      1
      ·
      30 days ago

      Version 2. I realized last night that my initial approach was way more complicated than it needed to be…

      import Data.List
      import Data.Semigroup
      
      maxJolt :: Int -> [Char] -> Int
      maxJolt r xs = read $ go r (length xs) xs
        where
          go r n xs =
            (\(Arg x xs) -> x : xs) . maximum $
              do
                (n', x : xs') <- zip (reverse [r .. n]) (tails xs)
                return . Arg x $ if r == 1 then [] else go (r - 1) (n' - 1) xs'
      
      main = do
        input <- lines <$> readFile "input03"
        mapM_ (print . sum . (`map` input) . maxJolt) [2, 12]