From: Neil Smith Date: Wed, 11 Dec 2024 12:03:17 +0000 (+0000) Subject: Done day 11 X-Git-Url: https://git.njae.me.uk/?a=commitdiff_plain;h=c6475b03d2ddd9bd9b51bc2ee9a212dbcbc8be53;p=advent-of-code-24.git Done day 11 --- diff --git a/advent11/Main.hs b/advent11/Main.hs new file mode 100644 index 0000000..e6c72f6 --- /dev/null +++ b/advent11/Main.hs @@ -0,0 +1,52 @@ +-- Writeup at https://work.njae.me.uk/2024/12/11/advent-of-code-2024-day-11/ + +import AoC + +-- import Data.List +import Data.Text (Text) +import qualified Data.Text.IO as TIO +import Data.Attoparsec.Text -- hiding (take, takeWhile) +import Data.IntMultiSet (IntMultiSet) +import qualified Data.IntMultiSet as MS + +main :: IO () +main = + do dataFileName <- getDataFileName + text <- TIO.readFile dataFileName + let stones = successfulParse text + -- print stones + -- putStrLn $ unlines $ fmap show $ take 7 $ iterate blink stones + print $ part1 stones + print $ part2 stones + +part1, part2 :: [Int] -> Int +part1 stones = length $ (!! 25) $ iterate blink stones +part2 stonesList = MS.size $ (!! 75) $ iterate blinkMS stones + where stones = MS.fromList stonesList + +blink :: [Int] -> [Int] +blink = concatMap expandStone + +blinkMS :: IntMultiSet -> IntMultiSet +blinkMS = MS.concatMap expandStone + +expandStone :: Int -> [Int] +expandStone 0 = [1] +expandStone n + | isEvenLen = [read nS1, read nS2] + | otherwise = [n * 2024] + where nStr = show n + nSL = length nStr + isEvenLen = nSL `mod` 2 == 0 + (nS1, nS2) = splitAt (nSL `div` 2) nStr + +-- parse the input file + +stonesP :: Parser [Int] +stonesP = decimal `sepBy` " " + +successfulParse :: Text -> [Int] +successfulParse input = + case parseOnly stonesP input of + Left _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err + Right stones -> stones diff --git a/adventofcode24.cabal b/adventofcode24.cabal index a188378..2f3eb9c 100644 --- a/adventofcode24.cabal +++ b/adventofcode24.cabal @@ -14,10 +14,10 @@ extra-doc-files: CHANGELOG.md -- extra-source-files: common warnings - ghc-options: -Wall + ghc-options: -Wall common common-modules - other-modules: AoC + other-modules: AoC common common-extensions default-extensions: AllowAmbiguousTypes @@ -63,7 +63,7 @@ library executable adventofcode24 import: warnings main-is: Main.hs - -- other-modules: + -- other-modules: AoC -- other-extensions: build-depends: base >=4.20, @@ -128,4 +128,8 @@ executable advent10 import: common-extensions, build-directives main-is: advent10/Main.hs build-depends: linear, array, mtl - \ No newline at end of file + +executable advent11 + import: common-extensions, build-directives + main-is: advent11/Main.hs + build-depends: attoparsec, text, multiset