From ad760a6c83e1083ddecf4acabed3827f198e5313 Mon Sep 17 00:00:00 2001 From: pingu Date: Wed, 11 Dec 2024 10:28:20 +0100 Subject: [PATCH] 11 part 2 done --- aoc.cabal | 1 + app/11.hs | 34 +++++++++++++++++----------------- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/aoc.cabal b/aoc.cabal index 003af77..413ff75 100644 --- a/aoc.cabal +++ b/aoc.cabal @@ -122,6 +122,7 @@ executable 11 -- other-extensions: build-depends: base ^>=4.18.2.1 , split + , containers hs-source-dirs: app default-language: GHC2021 executable 12 diff --git a/app/11.hs b/app/11.hs index 1d7280e..e9816ed 100644 --- a/app/11.hs +++ b/app/11.hs @@ -1,37 +1,37 @@ -{-# LANGUAGE LambdaCase #-} module Main where import Data.Functor import Data.List.Split +import Data.IntMap (IntMap) +import qualified Data.IntMap as IM -parse :: String -> [Int] -parse = (read <$>) . words +parse :: String -> IntMap Int +parse = foldr (flip (IM.insertWith (+)) 1 . read) mempty . words -rules :: [(Int -> Bool, Int -> [Int])] +rules :: [(Int -> Bool, Int -> IntMap Int)] rules = [ - ((==0), const [1]) - ,(even . length . show, \a -> let b = show a; s = length b in chunksOf (s `div` 2) b <&> read) - ,(const otherwise, pure . (*2024)) + ((==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)) ] -applyRule :: Int -> [Int] +applyRule :: Int -> IntMap Int applyRule i = head . filter (/= mempty) $ rules >>= \(f,g) -> if f i then pure $ g i else pure mempty -step :: [Int] -> [Int] -step = (applyRule =<<) +step :: IntMap Int -> IntMap Int +step = IM.foldrWithKey (\s c n -> IM.unionWith (+) n ((c*) <$> applyRule s)) mempty applyAmount :: Int -> a -> (a -> a) -> a applyAmount 0 a _ = a applyAmount n a f = f $ applyAmount (n-1) a f -solve1 :: [Int] -> Int -solve1 = length . flip (applyAmount 25) step - -solve2 :: [Int] -> Int -solve2 = undefined +solve :: Int -> IntMap Int -> Int +solve i = sum . IM.elems . flip (applyAmount i) step main :: IO () main = readFile "inputs/11" <&> parse >>= \i -> - print (solve1 i) >> - print (solve2 i) + print (solve 25 i) >> + print (solve 75 i)