Cipher Discussions | Algorithms | HackerRank
  • + 0 comments

    Haskell

    Missed three -- not sure why, but not spending more time on it.

    module Main where
    
    import Data.Foldable (Foldable (toList))
    import Data.Sequence (Seq, fromList, index, splitAt, (<|), (|>))
    import qualified Data.Sequence  as Seq
    
    cxor :: Char -> Char -> Char
    cxor '0' '0' = '0'
    cxor '1' '1' = '0'
    cxor _ _ = '1'
    
    solve2 :: Int -> Int -> String -> String
    solve2 n k e = go e solseq bsum
      where
        k' = k - 1
        solseq = fromList $ replicate k' '0'
        bsum = '0'
        go :: String -> Seq Char -> Char -> String
        go "" acc _ = drop k' $ reverse $ drop k' $ toList acc
        go (x : xs) acc bsum =
            let newC = x `cxor` bsum
                acc' = (newC <| acc)
                bsum' = newC `cxor` bsum `cxor` index acc' k'
             in go xs acc' bsum'
    
    main :: IO ()
    main = do
        [n, k] <- map read . words <$> getLine
        e <- getLine
        putStrLn $ solve2 n k e
        putStrLn ""