From 5890a28fd2161ac0c003fae8d26ae88e2fd687eb Mon Sep 17 00:00:00 2001 From: Laura Orvokki Kursula Date: Mon, 9 Dec 2024 11:12:10 +0100 Subject: 9-1 --- 9-1.hs | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 9-1.hs diff --git a/9-1.hs b/9-1.hs new file mode 100644 index 0000000..11b186d --- /dev/null +++ b/9-1.hs @@ -0,0 +1,51 @@ +import Data.Foldable (toList) +import Data.Sequence hiding (zip) +import Prelude hiding (replicate) + +type FS = Seq (Maybe Int) + +showFS :: FS -> String +showFS = Prelude.reverse . go [] + where + go :: String -> FS -> String + go res Empty = res + go res (x :<| xs) = go (f x : res) xs + + f :: Maybe Int -> Char + f Nothing = '.' + f (Just x) = head $ show x + +rearrange :: FS -> FS -> FS +rearrange result Empty = result +rearrange result (x@(Just _) :<| rest) = + rearrange (result :|> x) rest +rearrange result (Nothing :<| (rest :|> x@(Just _))) = + rearrange (result :|> x) rest +rearrange result (rest@(Nothing :<| _) :|> Nothing) = + rearrange result rest + +parse :: String -> FS +parse = go 0 Empty + where + go :: Int -> FS -> String -> FS + go _ res [] = res + go n res (x:xs) = go' (n+1) (res <> f x (Just n)) xs + + go' :: Int -> FS -> String -> FS + go' _ res [] = res + go' n res (x:xs) = go n (res <> f x Nothing) xs + + f :: Char -> Maybe Int -> FS + f x y = let n = read . pure $ x + in replicate n y + +catMaybes :: Seq (Maybe a) -> Seq a +catMaybes Empty = Empty +catMaybes (Nothing :<| xs) = catMaybes xs +catMaybes (Just x :<| xs) = x :<| catMaybes xs + +checksum :: FS -> Int +checksum = sum . fmap (uncurry (*)) . zip [0..] . toList . catMaybes + +main :: IO () +main = getLine >>= print . checksum . rearrange Empty . parse -- cgit v1.2.3