From 4a1ab47f3a009faca39cd483030f69b1ab28d686 Mon Sep 17 00:00:00 2001 From: Amneesh Singh Date: Mon, 2 Dec 2024 19:27:15 +0530 Subject: [PATCH] day 2 Signed-off-by: Amneesh Singh --- aoc2024.cabal | 6 ++++++ src/P2.hs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 src/P2.hs diff --git a/aoc2024.cabal b/aoc2024.cabal index 9809743..1003cc5 100644 --- a/aoc2024.cabal +++ b/aoc2024.cabal @@ -24,3 +24,9 @@ executable p1 hs-source-dirs: src main-is: P1.hs build-depends: libaoc + +executable p2 + import: common + hs-source-dirs: src + main-is: P2.hs + build-depends: libaoc diff --git a/src/P2.hs b/src/P2.hs new file mode 100644 index 0000000..e980517 --- /dev/null +++ b/src/P2.hs @@ -0,0 +1,36 @@ +module Main where + +import qualified AoC as A (extract) +import Data.List (inits, tails) +import Text.Parsec (char, digit, many1, newline, parse, sepBy1, sepEndBy1) +import Text.Parsec.String (Parser) + +parseReports :: Parser [[Int]] +parseReports = + sepEndBy1 + (sepBy1 (read <$> many1 digit) (char ' ')) + newline + +safe :: [Int] -> Bool +safe xs = + let differences :: [Int] + differences = zipWith (-) (tail xs) xs + in all (\x -> (x >= 1) && (x <= 3)) differences || all (\x -> (x <= -1) && (x >= -3)) differences + +part1 :: [[Int]] -> Int +part1 = length . filter safe + +part2 :: [[Int]] -> Int +part2 = length . filter dampSafe + where + dampSafe :: [Int] -> Bool + dampSafe xs = any safe (zipWith (++) (inits xs) (tail (tails xs))) + +main :: IO () +main = + do + raw <- readFile "./inputs/p2.in" + -- parse the input + let reports = A.extract $ parse parseReports "" raw + putStr "Part 1: " >> print (part1 reports) + putStr "Part 2: " >> print (part2 reports)