Skip to content

Instantly share code, notes, and snippets.

@skatenerd
Last active December 9, 2023 23:44
Show Gist options
  • Save skatenerd/293e5f2c072f9562ea32764865ed0487 to your computer and use it in GitHub Desktop.
Save skatenerd/293e5f2c072f9562ea32764865ed0487 to your computer and use it in GitHub Desktop.
Day Nine 2023
{-# LANGUAGE OverloadedStrings #-}
module DayNine where
import qualified Data.Text as T
import qualified Text.Read as TR
import qualified Data.List as L
import Safe (atMay, tailMay)
import qualified Data.Maybe as M
import Lib (operateOnFile)
derivative = L.unfoldr calculateDifference
where calculateDifference items = do
firstElement <- items `atMay` 0
secondElement <- items `atMay` 1
tail <- tailMay items
return (secondElement - firstElement, tail)
allDerivatives :: [Int] -> [[Int]]
allDerivatives f = takeWhile notDone $ iterate derivative f
where notDone = any (/= 0)
seeds = (map head) . allDerivatives
integrate seed [] = []
integrate seed derivative@(h:t) = (seed) : (integrate (seed + h) t)
generify f = foldr integrate (repeat 0) (seeds f)
extrapolatedValue f = (generify f) !! (length f)
testInput :: [T.Text]
testInput = ["0 3 6 9 12 15",
"1 3 6 10 15 21",
"10 13 16 21 30 45"]
partOne lines = sum $ map extrapolatedValue $ parsed
where parsed :: [[Int]]
parsed = map (M.catMaybes . (map readString) . (T.split (== ' '))) lines
readString = TR.readMaybe . T.unpack
partTwo lines = sum $ map (extrapolatedValue . reverse) $ parsed
where parsed :: [[Int]]
parsed = map (M.catMaybes . (map readString) . (T.split (== ' '))) lines
readString = TR.readMaybe . T.unpack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment