Add solution to day 2.

This commit is contained in:
Hans Goor 2024-12-02 17:13:15 +01:00
parent 1b2a5ef895
commit 8f579d529a
Signed by: eyedevelop
SSH key fingerprint: SHA256:Td89veptDEwCV8J3fjqnknNk7SbwzedYhauyC2nFBYg
5 changed files with 1079 additions and 2 deletions

View file

@ -0,0 +1,47 @@
module Main (main) where
-- | Part 1
type Report = [Int]
grabReports :: String -> [Report]
grabReports = map (map (\x -> read x :: Int) . words) . lines
isReportSafeWith :: (Int -> Int -> Bool) -> Report -> Bool
isReportSafeWith _ [] = True
isReportSafeWith _ [_] = True
isReportSafeWith f (x : y : xs) = f x y && isReportSafeWith f (y : xs)
reportDecreasing :: Int -> Int -> Bool
reportDecreasing x y = 1 <= x - y && x - y <= 3
reportIncreasing :: Int -> Int -> Bool
reportIncreasing x y = 1 <= y - x && y - x <= 3
isReportSafe :: Report -> Bool
isReportSafe report = isReportSafeWith reportDecreasing report || isReportSafeWith reportIncreasing report
part1 :: String -> IO ()
part1 = print . length . filter isReportSafe . grabReports
-- | Part 2
removeItem :: Int -> Report -> Report
removeItem n report = removeItem' n report 0
where
removeItem' :: Int -> Report -> Int -> Report
removeItem' _ [] _ = []
removeItem' n' (r : rs) i
| n' == i = removeItem' n' rs (i + 1)
| otherwise = r : removeItem' n' rs (i + 1)
reportPermutations :: Report -> [Report]
reportPermutations report = report : [removeItem i report | i <- [0 .. length report - 1]]
isReportSafePerm :: Report -> Bool
isReportSafePerm report = any isReportSafe (reportPermutations report)
part2 :: String -> IO ()
part2 = print . length . filter isReportSafePerm . grabReports
-- | Main
main :: IO ()
main = readFile "resources/day2.txt" >>= part2

View file

@ -37,7 +37,7 @@ library
base >=4.7 && <5
default-language: Haskell2010
executable aoc2024-day1
executable day1
main-is: Day1.hs
other-modules:
Paths_haskell
@ -51,6 +51,20 @@ executable aoc2024-day1
, haskell
default-language: Haskell2010
executable day2
main-is: Day2.hs
other-modules:
Paths_haskell
autogen-modules:
Paths_haskell
hs-source-dirs:
app/day2
ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints -threaded -rtsopts -with-rtsopts=-N
build-depends:
base >=4.7 && <5
, haskell
default-language: Haskell2010
test-suite haskell-test
type: exitcode-stdio-1.0
main-is: Spec.hs

View file

@ -37,7 +37,7 @@ library:
source-dirs: src
executables:
aoc2024-day1:
day1:
main: Day1.hs
source-dirs: app/day1
ghc-options:
@ -47,6 +47,16 @@ executables:
dependencies:
- haskell
day2:
main: Day2.hs
source-dirs: app/day2
ghc-options:
- -threaded
- -rtsopts
- -with-rtsopts=-N
dependencies:
- haskell
tests:
haskell-test:
main: Spec.hs

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,6 @@
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9