Day ten part two

This commit is contained in:
2024-12-11 00:48:54 +01:00
parent ae16418ae8
commit c255b82f2d
3 changed files with 39 additions and 0 deletions

View File

@@ -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)