Skip to content

Commit

Permalink
day 9
Browse files Browse the repository at this point in the history
  • Loading branch information
alexjercan committed Dec 9, 2023
1 parent 27c7c9f commit b5c12d6
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 2 deletions.
3 changes: 3 additions & 0 deletions aoc.sh
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,6 @@ stack exec day07 < input/day07.input

echo -e "${IRed}--- Day 8: Haunted Wasteland ---${Color_Off}"
stack exec day08 < input/day08.input

echo -e "${IYellow}--- Day 9: Mirage Maintenance ---${Color_Off}"
stack exec day09 < input/day09.input
1 change: 1 addition & 0 deletions aoc2023.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,7 @@ test-suite spec
TestDay06
TestDay07
TestDay08
TestDay09
Paths_aoc2023
autogen-modules:
Paths_aoc2023
Expand Down
28 changes: 26 additions & 2 deletions src/Day09.hs
Original file line number Diff line number Diff line change
@@ -1,10 +1,34 @@
module Day09 (main, part1, part2) where

parse :: String -> [[Int]]
parse = map (map read . words) . lines

diff :: [Int] -> [Int]
diff = zipWith (-) <$> tail <*> id

prediction :: [Int] -> Int
prediction xs = fst $ until stop step (0, xs)
where
step :: (Int, [Int]) -> (Int, [Int])
step (p, ys) = (p + last ys, diff ys)
stop :: (Int, [Int]) -> Bool
stop (_, ys) = all (== 0) ys

part1 :: String -> String
part1 = id
part1 = show . sum . map prediction . parse

prediction' :: [Int] -> Int
prediction' xs = foldl merge 0 $ fst $ until stop step ([], xs)
where
step :: ([Int], [Int]) -> ([Int], [Int])
step (ps, ys) = (head ys : ps, diff ys)
stop :: ([Int], [Int]) -> Bool
stop (_, ys) = all (== 0) ys
merge :: Int -> Int -> Int
merge acc x = x - acc

part2 :: String -> String
part2 = const ""
part2 = show . sum . map prediction' . parse

solve :: String -> String
solve input = "Part 1: " ++ part1 input ++ "\nPart 2: " ++ part2 input ++ "\n"
Expand Down
2 changes: 2 additions & 0 deletions test/Main.hs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import TestDay05
import TestDay06
import TestDay07
import TestDay08
import TestDay09

main :: IO ()
main = do
Expand All @@ -19,3 +20,4 @@ main = do
TestDay06.test
TestDay07.test
TestDay08.test
TestDay09.test
22 changes: 22 additions & 0 deletions test/TestDay09.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module TestDay09 (test) where

import Day09
import Test.Hspec

input :: String
input = "0 3 6 9 12 15\n 1 3 6 10 15 21\n10 13 16 21 30 45"

test1 :: Expectation
test1 = part1 input `shouldBe` "114"

test2 :: Expectation
test2 = part2 input `shouldBe` "2"

test :: IO ()
test = hspec $ do
describe "day09" $ do
describe "part1" $ do
it "should work for the examples" test1

describe "part2" $ do
it "should work for the examples" test2

0 comments on commit b5c12d6

Please sign in to comment.