From c255b82f2dbad2306d29457b98ef3e85277bab2b Mon Sep 17 00:00:00 2001 From: Siphalor Date: Wed, 11 Dec 2024 00:48:54 +0100 Subject: [PATCH] Day ten part two --- day-10-haskell/app/Main.hs | 5 +++++ day-10-haskell/day10-haskell.cabal | 1 + day-10-haskell/src/Task2.hs | 33 ++++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 day-10-haskell/src/Task2.hs diff --git a/day-10-haskell/app/Main.hs b/day-10-haskell/app/Main.hs index ba1f16a..f73af2c 100644 --- a/day-10-haskell/app/Main.hs +++ b/day-10-haskell/app/Main.hs @@ -2,6 +2,7 @@ module Main (main) where import System.Environment.Blank ( getArgs ) import Task1 (task1) +import Task2 (task2) main :: IO () main = do @@ -11,4 +12,8 @@ main = do input <- readFile file result <- task1 input print result + ["2", file] -> do + input <- readFile file + result <- task2 input + print result _ -> error "Usage: <1|2> " diff --git a/day-10-haskell/day10-haskell.cabal b/day-10-haskell/day10-haskell.cabal index 59de0e1..93de509 100644 --- a/day-10-haskell/day10-haskell.cabal +++ b/day-10-haskell/day10-haskell.cabal @@ -22,6 +22,7 @@ library exposed-modules: Common Task1 + Task2 hs-source-dirs: src ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints diff --git a/day-10-haskell/src/Task2.hs b/day-10-haskell/src/Task2.hs new file mode 100644 index 0000000..30eda46 --- /dev/null +++ b/day-10-haskell/src/Task2.hs @@ -0,0 +1,33 @@ +module Task2 (task2) where + +import Common +import Data.List ((!?)) +import Control.Monad (join) +import Flow + +task2 :: String -> IO Int +task2 input = let worldMap = parseMap input + trailheads = findInMap 0 worldMap + in trailheads >>= followToHills worldMap |> map length |> sum |> return + where + followToHills :: WorldMap -> Position -> [Position] + followToHills worldMap trailhead = followAllUp 0 [trailhead] + where + followAllUp :: Int -> [Position] -> [Position] + followAllUp 9 positions = positions + -- Only change was to *remove* the set functions in the next line, lol + followAllUp height positions = positions |> map followUp |> join |> followAllUp (height + 1) + where + followUp :: Position -> [Position] + followUp pos = [(0, -1), (-1, 0), (0, 1), (1, 0)] |> map (offset pos) |> filter canGoUp + + canGoUp :: Position -> Bool + canGoUp (x, y) = case worldMap !? y of + Nothing -> False + Just line -> case line !? x of + Nothing -> False + Just Nothing -> False + Just (Just element) -> element == height + 1 + + offset :: Position -> Position -> Position + offset (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)