Skip to content

Instantly share code, notes, and snippets.

@marvhus
Created December 10, 2023 18:01
Show Gist options
  • Save marvhus/dd9790efb5f3201625c9a6a58608c7e4 to your computer and use it in GitHub Desktop.
Save marvhus/dd9790efb5f3201625c9a6a58608c7e4 to your computer and use it in GitHub Desktop.
Day 9 of AoC 2023 in Haskell. No bullshit, just standard stuff.
getPairs :: [Int] -> [(Int, Int)]
getPairs [] = []
getPairs [_] = []
getPairs (x:y:xs) = (x,y) : getPairs (y:xs)
getDiff :: [(Int, Int)] -> [Int]
getDiff [] = []
getDiff ((x1, x2):xs) = (x2 - x1) : getDiff xs
generate :: [Int] -> [[Int]]
generate xs =
let diff = getDiff . getPairs $ xs
next = generate diff
in xs : if all (== 0) diff
then [diff]
else next
solve :: ([Int] -> Int -> Int) -> [[Int]] -> Int
solve f = foldr f 0
part1 :: [[Int]] -> Int
part1 = sum . map (solve f . generate)
where
f xs y = last xs + y
part2 :: [[Int]] -> Int
part2 = sum . map (solve f . generate)
where
f xs y = head xs - y
prepare :: String -> [[Int]]
prepare = map (map read . words) . lines
main :: IO ()
main = do
inFile <- readFile "input.txt"
putStrLn $ "Part 1: " ++ (show . part1 . prepare) inFile
putStrLn $ "Part 2: " ++ (show . part2 . prepare) inFile
putStrLn "Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment