summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLaura Orvokki Kursula <lav@vampires.gay>2024-12-09 11:12:10 +0100
committerLaura Orvokki Kursula <lav@vampires.gay>2024-12-09 11:30:53 +0100
commit5890a28fd2161ac0c003fae8d26ae88e2fd687eb (patch)
treea1ac827088235e69bc731f3bdd0e22e81c2c67ea
parentc5f4630568d74ff30deb5c79354df02d21f20220 (diff)
downloadaoc2024-5890a28fd2161ac0c003fae8d26ae88e2fd687eb.tar.gz
aoc2024-5890a28fd2161ac0c003fae8d26ae88e2fd687eb.zip
9-1
-rw-r--r--9-1.hs51
1 files changed, 51 insertions, 0 deletions
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