diff options
Diffstat (limited to '9-1.hs')
-rw-r--r-- | 9-1.hs | 51 |
1 files changed, 51 insertions, 0 deletions
@@ -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 |