refactor day 2

This commit is contained in:
Victor Martinez 2025-03-12 15:59:45 +01:00
parent fc76286ccd
commit 5bd3f594c4

View file

@ -16,7 +16,6 @@ partOne contents = length . filter isSafeReport <$> parseInput contents
partTwo :: String -> Either Error Int partTwo :: String -> Either Error Int
partTwo contents = length . filter isSafeReportWithTolerance <$> parseInput contents partTwo contents = length . filter isSafeReportWithTolerance <$> parseInput contents
where where
isSafeReportWithTolerance :: Report -> Bool
isSafeReportWithTolerance xs = isSafeReport xs || aux [] xs isSafeReportWithTolerance xs = isSafeReport xs || aux [] xs
where where
aux left [] = isSafeReport left aux left [] = isSafeReport left
@ -24,17 +23,12 @@ partTwo contents = length . filter isSafeReportWithTolerance <$> parseInput cont
isSafeReport :: Report -> Bool isSafeReport :: Report -> Bool
isSafeReport xs = isSafeReportWith isSafeIncrease xs || isSafeReportWith isSafeDecrease xs isSafeReport xs = isSafeReportWith isSafeIncrease xs || isSafeReportWith isSafeDecrease xs
where
isSafeReportWith :: (Level -> Level -> Bool) -> Report -> Bool isSafeReportWith validator (x : y : xs') = validator x y && isSafeReportWith validator (y : xs')
isSafeReportWith validator (x : y : xs) = validator x y && isSafeReportWith validator (y : xs) isSafeReportWith _ [_] = True
isSafeReportWith _ [_] = True isSafeReportWith _ [] = False
isSafeReportWith _ [] = False isSafeIncrease x y = (x - y) > 0 && (x - y) < 4
isSafeDecrease x y = isSafeIncrease y x
isSafeIncrease :: Level -> Level -> Bool
isSafeIncrease x y = (x - y) > 0 && (x - y) < 4
isSafeDecrease :: Level -> Level -> Bool
isSafeDecrease x y = isSafeIncrease y x
parseInput :: String -> Either Error [Report] parseInput :: String -> Either Error [Report]
parseInput contents = mapM parseReport (lines contents) parseInput contents = mapM parseReport (lines contents)