From 7f5f185eacc15623c02e6e06baecad6671780014 Mon Sep 17 00:00:00 2001 From: Neil Smith Date: Mon, 2 Dec 2024 09:38:35 +0000 Subject: [PATCH] Done day 2 --- advent02/Main.hs | 38 ++++++++++++++++++++++++++++++++++++++ adventofcode24.cabal | 5 +++++ 2 files changed, 43 insertions(+) create mode 100644 advent02/Main.hs diff --git a/advent02/Main.hs b/advent02/Main.hs new file mode 100644 index 0000000..a0f4534 --- /dev/null +++ b/advent02/Main.hs @@ -0,0 +1,38 @@ +-- Writeup at https://work.njae.me.uk/2024/12/02/advent-of-code-2024-day-2/ + +import AoC +import Data.List + +main :: IO () +main = + do dataFileName <- getDataFileName + text <- readFile dataFileName + let reports = fmap readLine $ lines text + print $ part1 reports + print $ part2 reports + +part1, part2 :: [[Int]] -> Int +part1 reports = length $ filter isSafe reports +part2 reports = length $ filter isSafe' reports + where isSafe' l = isSafe l || safeWhenDamped l + +isSafe, allSameSign, bigEnough, smallEnough, safeWhenDamped :: [Int] -> Bool +isSafe xs = allSameSign diffs && bigEnough diffs && smallEnough diffs + where diffs = zipWith (-) xs (tail xs) + +allSameSign xs + | all (>0) xs = True + | all (<0) xs = True + | otherwise = False + +bigEnough = all ((>= 1) . abs) +smallEnough = all ((<= 3) . abs) + +safeWhenDamped = (any isSafe) . damped + +damped :: [Int] -> [[Int]] +damped line = zipWith (++) (inits line) (drop 1 $ tails line) + +readLine :: String -> [Int] +readLine = (fmap read) . words + diff --git a/adventofcode24.cabal b/adventofcode24.cabal index f922676..565d1d9 100644 --- a/adventofcode24.cabal +++ b/adventofcode24.cabal @@ -76,3 +76,8 @@ executable advent01 import: warnings, common-extensions, build-directives, common-modules main-is: advent01/Main.hs build-depends: multiset + +executable advent02 + import: warnings, common-extensions, build-directives, common-modules + main-is: advent02/Main.hs + \ No newline at end of file -- 2.34.1