1
0
Fork 0
advent-of-code/2023/9.hs

28 lines
565 B
Haskell
Raw Normal View History

2023-12-09 21:29:49 -05:00
#!/usr/bin/env runhaskell
2023-12-09 21:33:58 -05:00
import Control.Monad (ap)
2023-12-09 21:29:49 -05:00
parseInput = map (map read . words) . lines
solve str = show (part1', part2')
where
input = parseInput str
part1' = part1 input
part2' = part2 input
2023-12-09 21:33:58 -05:00
part1 = sum . map next
part2 = sum . map prev
2023-12-09 21:29:49 -05:00
2023-12-09 21:33:58 -05:00
deltas = ap (zipWith subtract) tail
differentiate = takeWhile notAllZeros . iterate deltas
2023-12-09 21:29:49 -05:00
where
2023-12-09 21:33:58 -05:00
notAllZeros = not . all (0 ==)
2023-12-09 21:29:49 -05:00
2023-12-09 21:33:58 -05:00
next = sum . map last . differentiate
2023-12-09 21:29:49 -05:00
2023-12-09 21:33:58 -05:00
prev = foldl1 subtract . reverse . map head . differentiate
2023-12-09 21:29:49 -05:00
main = do
contents <- getContents
putStrLn $ solve contents