aoc-2021/day6/second.hs

33 lines
848 B
Haskell

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