Day 4: Perilous Pier

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
    3
    ·
    10 hours ago

    Haskell

    After some juggling to combine foldM and zipWithM ended up with quite a concise solution:

    {-# LANGUAGE OverloadedStrings #-}
    
    import Control.Arrow
    import Control.Monad
    import Data.List
    import Data.Maybe
    import Data.Text qualified as T
    import Data.Text.IO qualified as TIO
    
    findPatternLength w = find (pattern w) [1 ..]
    
    pattern w l = isJust $ foldM (zipWithM merge) (T.unpack $ T.replicate l "?") chunks
     where
      chunks = T.unpack <$> T.chunksOf l w
    
      merge a b
        | a == b = Just a
        | a == '?' = Just b
        | b == '?' = Just a
        | otherwise = Nothing
    
    part1 = fmap sum . mapM findPatternLength
    part2 = findPatternLength . T.concat
    
    main :: IO ()
    main = TIO.getContents >>= print . (part1 &&& part2) . T.lines
    
    • VegOwOtenks@lemmy.world
      link
      fedilink
      arrow-up
      2
      ·
      10 hours ago

      At first I wondered why you used Maybe instead of and when you check for isJust at the end anyways. I got it eventually, it’s for short-circuiting when merging does fail and to update the pattern while folding.