day6: Complete second puzzle
This commit is contained in:
parent
127d8a89cb
commit
3cfbae97b4
|
@ -6,28 +6,42 @@ main = do
|
||||||
let
|
let
|
||||||
fish = parseFish input
|
fish = parseFish input
|
||||||
(putStrLn . show . solution1) fish
|
(putStrLn . show . solution1) fish
|
||||||
|
(putStrLn . show . solution2) fish
|
||||||
|
|
||||||
solution1 :: [Int] -> Int
|
solution1 :: [Int] -> Int
|
||||||
solution1 = length . (simulateDays 80)
|
solution1 = sum . (simulateDays 79)
|
||||||
|
|
||||||
|
solution2 :: [Int] -> Int
|
||||||
|
solution2 = sum . (simulateDays 255)
|
||||||
|
|
||||||
parseFish :: String -> [Int]
|
parseFish :: String -> [Int]
|
||||||
parseFish = (map read) . (splitByString ",")
|
parseFish = (map read) . (splitByString ",")
|
||||||
|
|
||||||
simulateDays :: Int -> [Int] -> [Int]
|
initBuffer :: [Int] -> [Int]
|
||||||
simulateDays days fish = foldr (\f acc -> f acc) fish (replicate days tickDay)
|
initBuffer initialFish = map occurrences [0..8]
|
||||||
|
where
|
||||||
|
occurrences x = length (filter (==x) initialFish)
|
||||||
|
|
||||||
tickDay :: [Int] -> [Int]
|
simulateDays :: Int -> [Int] -> [Int]
|
||||||
tickDay [] = []
|
simulateDays days initialFish = foldl tickDay (initBuffer initialFish) [0..days]
|
||||||
tickDay (fish:otherFish)
|
where
|
||||||
| fish == 0 = 6:8:(tickDay otherFish)
|
tickDay :: [Int] -> Int -> [Int]
|
||||||
| otherwise = (fish - 1):(tickDay otherFish)
|
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
|
-- Tests
|
||||||
|
|
||||||
testInput = "3,4,3,1,2"
|
testInput = "3,4,3,1,2"
|
||||||
testParsed = parseFish testInput
|
testParsed = parseFish testInput
|
||||||
|
|
||||||
test1 = solution1 (parseFish testInput)
|
test1 = solution1 (parseFish testInput) -- 5934
|
||||||
|
test2 = solution2 (parseFish testInput) -- 26984457539
|
||||||
testTick = (tickDay . tickDay) testParsed
|
|
||||||
testSimulate = length (simulateDays 80 testParsed)
|
|
||||||
|
|
Loading…
Reference in a new issue