From 3cfbae97b472c1b56149db7dd22a520508bdae00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tristan=20Dani=C3=ABl=20Maat?= Date: Wed, 8 Dec 2021 03:29:11 +0000 Subject: [PATCH] day6: Complete second puzzle --- 6/fishexploder.hs | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/6/fishexploder.hs b/6/fishexploder.hs index f676ca2..f3283e8 100644 --- a/6/fishexploder.hs +++ b/6/fishexploder.hs @@ -6,28 +6,42 @@ main = do let fish = parseFish input (putStrLn . show . solution1) fish + (putStrLn . show . solution2) fish solution1 :: [Int] -> Int -solution1 = length . (simulateDays 80) +solution1 = sum . (simulateDays 79) + +solution2 :: [Int] -> Int +solution2 = sum . (simulateDays 255) parseFish :: String -> [Int] parseFish = (map read) . (splitByString ",") -simulateDays :: Int -> [Int] -> [Int] -simulateDays days fish = foldr (\f acc -> f acc) fish (replicate days tickDay) +initBuffer :: [Int] -> [Int] +initBuffer initialFish = map occurrences [0..8] + where + occurrences x = length (filter (==x) initialFish) -tickDay :: [Int] -> [Int] -tickDay [] = [] -tickDay (fish:otherFish) - | fish == 0 = 6:8:(tickDay otherFish) - | otherwise = (fish - 1):(tickDay otherFish) +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) - -testTick = (tickDay . tickDay) testParsed -testSimulate = length (simulateDays 80 testParsed) +test1 = solution1 (parseFish testInput) -- 5934 +test2 = solution2 (parseFish testInput) -- 26984457539