Day 1: Secret Entrance

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

  • LeixB@lemmy.world
    link
    fedilink
    arrow-up
    4
    ·
    edit-2
    5 days ago

    Haskell

    import Control.Arrow
    import Control.Monad
    import Control.Monad.Writer.Strict
    import Data.Char
    import Data.Functor
    import Text.ParserCombinators.ReadP
    
    n = 100
    start = 50
    
    parse = fst . last . readP_to_S (endBy rotation (char '\n'))
      where
        rotation = (*) <$> ((char 'L' $> (-1)) <++ (char 'R' $> 1)) <*> (read <$> munch isDigit)
    
    part1 = length . filter (== 0) . fmap (`mod` n) . scanl (+) start
    
    spins :: Int -> Int -> Writer [Int] Int
    spins acc x = do
        when (abs x >= n) . tell . pure $ abs x `div` n -- full loops
        let res = acc + (x `rem` n)
            res' = res `mod` n
    
        when (res /= res') . tell . pure $ 1
    
        return res'
    
    part2 = sum . execWriter . foldM spins start
    
    main = getContents >>= (print . (part1 &&& part2) . parse)
    
    • VegOwOtenks@lemmy.world
      link
      fedilink
      arrow-up
      2
      ·
      5 days ago

      I think that’s a really cool usage of the Writer Monad. I thought about the State Monad but didn’t end up using it. Was too hectic for me. Thanks for showing and sharing this!