@@ -7,22 +7,29 @@ import qualified Data.Matrix as M
7
7
import Data.Point (Point )
8
8
9
9
partOne :: String -> Int
10
- partOne input = length $ filter (uncurry (isReachable matrix)) candidates
10
+ partOne input = length $ filter (( > 0 ) . uncurry (rating matrix)) candidates
11
11
where
12
12
matrix = parseMatrix input
13
- trailHeads = M. points $ M. filter (== 0 ) matrix
14
- trailEnds = M. points $ M. filter (== 9 ) matrix
15
- candidates = concatMap (zip trailHeads . repeat ) trailEnds
13
+ candidates = possibleTrails matrix
16
14
17
- isReachable :: Matrix Int -> Point -> Point -> Bool
18
- isReachable matrix x y = go (getCandidates 1 x) [y] 1
15
+ partTwo :: String -> Int
16
+ partTwo input = sum $ map ( uncurry (rating matrix)) candidates
19
17
where
20
- go :: [Point ] -> [Point ] -> Int -> Bool
21
- go _ _ 9 = False
18
+ matrix = parseMatrix input
19
+ candidates = possibleTrails matrix
20
+
21
+ rating :: Matrix Int -> Point -> Point -> Int
22
+ rating matrix x y = go (getCandidates 1 x) [y] 1
23
+ where
24
+ go :: [Point ] -> [Point ] -> Int -> Int
25
+ go _ _ 6 = 0
22
26
go leftFront rightFront step =
23
27
let leftFront' = concatMap (getCandidates (1 + step)) leftFront
24
28
rightFront' = concatMap (getCandidates (9 - step)) rightFront
25
- in not (null (leftFront `intersect` rightFront)) || go leftFront' rightFront' (step + 1 )
29
+ intersection = intersect leftFront rightFront
30
+ in if not (null intersection)
31
+ then length intersection
32
+ else go leftFront' rightFront' (step + 1 )
26
33
27
34
getCandidates :: Int -> Point -> [Point ]
28
35
getCandidates value (row, col) =
@@ -36,8 +43,11 @@ isReachable matrix x y = go (getCandidates 1 x) [y] 1
36
43
)
37
44
$ zip positions values
38
45
39
- partTwo :: String -> Int
40
- partTwo input = 0
46
+ possibleTrails :: Matrix Int -> [(Point , Point )]
47
+ possibleTrails matrix =
48
+ let trailHeads = M. points $ M. filter (== 0 ) matrix
49
+ trailEnds = M. points $ M. filter (== 9 ) matrix
50
+ in concatMap (zip trailHeads . repeat ) trailEnds
41
51
42
52
parseMatrix :: String -> Matrix Int
43
53
parseMatrix = M. buildMatrix . map (map digitToInt) . lines
0 commit comments