-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.hs
64 lines (51 loc) · 1.47 KB
/
run.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeApplications #-}
import AoC.Grid
import Control.Monad (guard)
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.Set (Set)
import qualified Data.Set as Set
type N = Int
type Input = MapGrid N
parseAll :: String -> Input
parseAll = parseMapGrid (read @N . pure)
neighbors :: (Int, Int) -> [(Int, Int)]
neighbors (x, y) =
[ (x - 1, y )
, (x + 1, y )
, (x , y - 1)
, (x , y + 1)
]
ordNub :: Ord a => [a] -> [a]
ordNub = Set.toList . Set.fromList
trails :: Input -> (Int, Int) -> [(Int, Int)]
trails g sp = go 0 [sp]
where go 9 ps = ps
go i ps =
let next = do
p <- ps
p' <- neighbors p
Just j <- pure $ g HashMap.!? p'
guard $ j == i + 1
pure p'
in
go (i + 1) next
startPoints :: Input -> [(Int, Int)]
startPoints = map fst . filter ((== 0) . snd) . HashMap.toList
part1 :: Input -> Int
part1 g = sum . map (length . ordNub) $ map (trails g) (startPoints g)
part2 :: Input -> Int
part2 g = sum . map length $ map (trails g) (startPoints g)
main :: IO ()
main = main' "input.txt"
exampleMain :: IO ()
exampleMain = main' "example.txt"
main' :: FilePath -> IO ()
main' file = do
input <- parseAll <$> readFile file
print (part1 input)
print (part2 input)