day6: Complete second puzzle

main
Tristan Daniël Maat 2021-12-08 03:29:11 +00:00
parent 127d8a89cb
commit 3cfbae97b4
Signed by: tlater
GPG Key ID: 49670FD774E43268
1 changed files with 26 additions and 12 deletions

View File

@ -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