From a06b44e74a39a37bf6e124dca517714d73748bcf Mon Sep 17 00:00:00 2001 From: opfez Date: Tue, 7 Dec 2021 21:48:52 +0100 Subject: [PATCH] day 6 --- day6/first.hs | 18 ++++++++++++++++++ day6/input | 1 + day6/second.hs | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+) create mode 100644 day6/first.hs create mode 100644 day6/input create mode 100644 day6/second.hs diff --git a/day6/first.hs b/day6/first.hs new file mode 100644 index 0000000..0f49db6 --- /dev/null +++ b/day6/first.hs @@ -0,0 +1,18 @@ +wordsWhen :: (a -> Bool) -> [a] -> [[a]] +wordsWhen pred s = + case dropWhile pred s of + [] -> [] + s' -> w : wordsWhen pred s'' + where (w, s'') = break pred s' + +parseFish :: String -> [Int] +parseFish = map read . wordsWhen (==',') + +simulate :: Int -> [Int] -> Int +simulate 0 fish = length fish +simulate days fish = + simulate (days-1) $ concatMap (\f -> if f == 0 + then [6,8] + else [f-1]) fish + +main = interact $ show . simulate 80 . parseFish diff --git a/day6/input b/day6/input new file mode 100644 index 0000000..13eab94 --- /dev/null +++ b/day6/input @@ -0,0 +1 @@ +5,1,4,1,5,1,1,5,4,4,4,4,5,1,2,2,1,3,4,1,1,5,1,5,2,2,2,2,1,4,2,4,3,3,3,3,1,1,1,4,3,4,3,1,2,1,5,1,1,4,3,3,1,5,3,4,1,1,3,5,2,4,1,5,3,3,5,4,2,2,3,2,1,1,4,1,2,4,4,2,1,4,3,3,4,4,5,3,4,5,1,1,3,2,5,1,5,1,1,5,2,1,1,4,3,2,5,2,1,1,4,1,5,5,3,4,1,5,4,5,3,1,1,1,4,5,3,1,1,1,5,3,3,5,1,4,1,1,3,2,4,1,3,1,4,5,5,1,4,4,4,2,2,5,5,5,5,5,1,2,3,1,1,2,2,2,2,4,4,1,5,4,5,2,1,2,5,4,4,3,2,1,5,1,4,5,1,4,3,4,1,3,1,5,5,3,1,1,5,1,1,1,2,1,2,2,1,4,3,2,4,4,4,3,1,1,1,5,5,5,3,2,5,2,1,1,5,4,1,2,1,1,1,1,1,2,1,1,4,2,1,3,4,2,3,1,2,2,3,3,4,3,5,4,1,3,1,1,1,2,5,2,4,5,2,3,3,2,1,2,1,1,2,5,3,1,5,2,2,5,1,3,3,2,5,1,3,1,1,3,1,1,2,2,2,3,1,1,4,2 diff --git a/day6/second.hs b/day6/second.hs new file mode 100644 index 0000000..d464d2a --- /dev/null +++ b/day6/second.hs @@ -0,0 +1,32 @@ +import Data.List + +wordsWhen :: (a -> Bool) -> [a] -> [[a]] +wordsWhen pred s = + case dropWhile pred s of + [] -> [] + s' -> w : wordsWhen pred s'' + where (w, s'') = break pred s' + +replaceNth :: Int -> a -> [a] -> [a] +replaceNth _ _ [] = error "too small index" +replaceNth 0 y (x:xs) = y : xs +replaceNth n y (x:xs) = x : replaceNth (n-1) y xs + +parseFish :: String -> [Integer] +parseFish = flip (++) [0,0,0] + . (:) 0 + . map (toInteger . length) + . group + . sort + . map (read :: String -> Integer) + . wordsWhen (==',') + +simulate :: Integer -> [Integer] -> Integer +simulate 0 fish = foldr1 (+) fish +simulate days fish = + simulate (days-1) newFish + where zeros = head fish + withEights = (tail fish) ++ [zeros] + newFish = replaceNth 6 (zeros + withEights !! 6) withEights + +main = interact $ show . simulate 256 . parseFish