aoc/app/11.hs

38 lines
1.1 KiB
Haskell
Raw Normal View History

2024-12-02 10:51:49 +00:00
module Main where
import Data.Functor
2024-12-11 08:28:42 +00:00
import Data.List.Split
2024-12-11 09:28:20 +00:00
import Data.IntMap (IntMap)
import qualified Data.IntMap as IM
2024-12-02 10:51:49 +00:00
2024-12-11 09:28:20 +00:00
parse :: String -> IntMap Int
parse = foldr (flip (IM.insertWith (+)) 1 . read) mempty . words
2024-12-02 10:51:49 +00:00
2024-12-11 09:28:20 +00:00
rules :: [(Int -> Bool, Int -> IntMap Int)]
2024-12-11 08:28:42 +00:00
rules =
[
2024-12-11 09:28:20 +00:00
((==0), const (IM.singleton 1 1))
,(even . length . show,
\a -> let b = show a; s = length b in
foldr (flip (IM.insertWith (+)) 1 . read) mempty (chunksOf (s `div` 2) b))
,(const otherwise, (`IM.singleton` 1) . (*2024))
2024-12-11 08:28:42 +00:00
]
2024-12-02 10:51:49 +00:00
2024-12-11 09:28:20 +00:00
applyRule :: Int -> IntMap Int
2024-12-11 08:28:42 +00:00
applyRule i = head . filter (/= mempty) $ rules >>= \(f,g) -> if f i then pure $ g i else pure mempty
2024-12-11 09:28:20 +00:00
step :: IntMap Int -> IntMap Int
step = IM.foldrWithKey (\s c n -> IM.unionWith (+) n ((c*) <$> applyRule s)) mempty
2024-12-11 08:28:42 +00:00
applyAmount :: Int -> a -> (a -> a) -> a
applyAmount 0 a _ = a
applyAmount n a f = f $ applyAmount (n-1) a f
2024-12-11 09:28:20 +00:00
solve :: Int -> IntMap Int -> Int
solve i = sum . IM.elems . flip (applyAmount i) step
2024-12-02 10:51:49 +00:00
main :: IO ()
main = readFile "inputs/11" <&> parse >>= \i ->
2024-12-11 09:28:20 +00:00
print (solve 25 i) >>
print (solve 75 i)