|
| 1 | +module Main where |
| 2 | + |
| 3 | +import Data.Bits |
| 4 | +import Data.List |
| 5 | +import Data.List.Split |
| 6 | +import Data.List.Unique |
| 7 | +import Data.Matrix (Matrix, (!)) |
| 8 | +import Data.Matrix qualified as Mat |
| 9 | +import Data.Set (Set) |
| 10 | +import Data.Set qualified as S |
| 11 | +import System.Environment |
| 12 | +-- TODO: Cleanup imports after day done |
| 13 | + |
| 14 | +type Input = (Matrix Int, [(Int, Int)]) |
| 15 | +type Output = Int |
| 16 | + |
| 17 | +data Dir = UP | LEFT | RIGHT | DOWN deriving (Show, Eq) |
| 18 | + |
| 19 | +parseInput :: String -> Input |
| 20 | +parseInput s = (mat, starts) |
| 21 | + where |
| 22 | + mat = Mat.fromLists . map (map (read . (:[]))) $ lines s |
| 23 | + starts = [(y, x) | y<-[1..Mat.nrows mat], x<-[1..Mat.ncols mat], mat ! (y,x) == 0] |
| 24 | + |
| 25 | +move :: (Int, Int) -> Dir -> (Int, Int) |
| 26 | +move (y, x) UP = (y-1, x) |
| 27 | +move (y, x) DOWN = (y+1, x) |
| 28 | +move (y, x) LEFT = (y, x-1) |
| 29 | +move (y, x) RIGHT = (y, x+1) |
| 30 | + |
| 31 | +isOut :: (Int, Int) -> (Int, Int) -> Bool |
| 32 | +isOut (width, height) (y, x) = x <= 0 || y <= 0 || x > width || y > height |
| 33 | + |
| 34 | +validEndTrails :: Matrix Int -> Int -> (Int, Int) -> [(Int, Int)] |
| 35 | +validEndTrails grid curr pos |
| 36 | + | isOut (Mat.ncols grid, Mat.nrows grid) pos = [] |
| 37 | + | grid ! pos /= curr + 1 = [] |
| 38 | + | grid ! pos == 9 = [pos] |
| 39 | + | otherwise = concat $ map (validEndTrails grid (grid ! pos) . move pos) [UP, DOWN, LEFT, RIGHT] |
| 40 | + |
| 41 | +part1 :: Input -> Output |
| 42 | +part1 (grid, pos) = sum $ map (length . sortUniq . validEndTrails grid (-1)) pos |
| 43 | + |
| 44 | +part2 :: Input -> Output |
| 45 | +part2 (grid, pos) = sum $ map (length . validEndTrails grid (-1)) pos |
| 46 | + |
| 47 | +main :: IO () |
| 48 | +main = do |
| 49 | + args <- getArgs |
| 50 | + content <- readFile (last args) |
| 51 | + let input = parseInput content |
| 52 | + |
| 53 | + print $ part1 input |
| 54 | + print $ part2 input |
0 commit comments