adventofcode-2021/6/fishexploder.hs

48 lines
1.2 KiB
Haskell

import Parsing (splitByString)
main :: IO ()
main = do
input <- getContents
let
fish = parseFish input
(putStrLn . show . solution1) fish
(putStrLn . show . solution2) fish
solution1 :: [Int] -> Int
solution1 = sum . (simulateDays 79)
solution2 :: [Int] -> Int
solution2 = sum . (simulateDays 255)
parseFish :: String -> [Int]
parseFish = (map read) . (splitByString ",")
initBuffer :: [Int] -> [Int]
initBuffer initialFish = map occurrences [0..8]
where
occurrences x = length (filter (==x) initialFish)
simulateDays :: Int -> [Int] -> [Int]
simulateDays days initialFish = foldl tickDay (initBuffer initialFish) [0..days]
where
tickDay :: [Int] -> Int -> [Int]
tickDay fish day = map fishMultiplier [0..length(fish)-1]
where
fishMultiplier :: Int -> Int
fishMultiplier i
| i == addedTo =
(fish !! i) + (fish !! dayFish)
| otherwise =
fish !! i
where
dayFish = day `rem` 9
addedTo = (dayFish + 7) `rem` 9
-- Tests
testInput = "3,4,3,1,2"
testParsed = parseFish testInput
test1 = solution1 (parseFish testInput) -- 5934
test2 = solution2 (parseFish testInput) -- 26984457539