import: common-extensions, build-directives
main-is: advent08/Main.hs
build-depends: text, attoparsec, containers
+
+executable advent09
+ import: common-extensions, build-directives
+ main-is: advent09/Main.hs
-- print $ desert
print $ part1 desert directions
print $ part2 desert directions
- -- print $ part3 desert directions
+ print $ part3 desert directions
part1, part2 :: Desert -> [Direction] -> Int
part1 desert directions = getSteps $ walk desert directions (State "AAA" 0)
gResults = fmap (walkWithCache desert directions M.empty) fromGoals
--- part3 desert directions = multiWalk desert directions M.empty starts
--- where starts = fmap (\s -> State s 0) $ startsOf desert
+part3 desert directions = multiWalk desert directions M.empty starts
+ where starts = fmap (\s -> State s 0) $ startsOf desert
--- multiWalk desert directions cache states@(s:ss)
--- | (all isGoal states) && (sameTime states) = states
--- | otherwise = multiWalk desert directions newCache $ sort (s':ss)
--- where (s', newCache) = walkWithCache desert directions cache s
+multiWalk desert directions cache states@(s:ss)
+ | (all isGoal states) && (sameTime states) = states
+ | otherwise = multiWalk desert directions newCache $ sort (s':ss)
+ where (s', newCache) = walkWithCache desert directions cache s
--- sameTime states = (length $ nub times) == 1
--- where times = fmap getSteps states
+sameTime states = (length $ nub times) == 1
+ where times = fmap getSteps states
walk :: Desert -> [Direction] -> State -> State
walk desert directions start = head $ dropWhile (not . isGoal) path
--- /dev/null
+-- Writeup at https://work.njae.me.uk/2023/12/09/advent-of-code-2023-day-09/
+
+import AoC
+import Data.List
+
+newtype Sequence = Sequence [[Int]] deriving (Show, Eq)
+
+main :: IO ()
+main =
+ do dataFileName <- getDataFileName
+ text <- readFile dataFileName
+ let histories = readInput text
+ -- print histories
+ let seqs = fmap (expand . Sequence . pure) histories
+ -- print seqs
+ -- let seqs' = fmap extend seqs
+ -- print seqs'
+ print $ part1 seqs
+ let rseqs = fmap (expand . Sequence . pure . reverse) histories
+ print $ part1 rseqs
+
+part1 :: [Sequence] -> Int
+part1 = sum . fmap (evaluate . extend)
+
+
+readInput :: String -> [[Int]]
+readInput = fmap (fmap read . words) . lines
+
+expand :: Sequence -> Sequence
+expand (Sequence xss)
+ | all (== 0) $ last xss = Sequence xss
+ | otherwise = expand $ Sequence $ xss ++ [differences $ last xss]
+
+differences :: [Int] -> [Int]
+differences xs = zipWith (-) (tail xs) xs
+
+extend :: Sequence -> Sequence
+extend (Sequence xss) = Sequence $ fst $ foldr extendRow ([], 0) xss
+
+extendRow :: [Int] -> ([[Int]], Int) -> ([[Int]], Int)
+extendRow row (seq, n) = ((row ++ [n']) : seq, n')
+ where n' = last row + n
+
+evaluate :: Sequence -> Int
+evaluate (Sequence xss) = last $ head xss