tangled
alpha
login
or
join now
eldridge.cam
/
advent-of-code
2
fork
atom
Advent of Code solutions
2
fork
atom
overview
issues
pulls
pipelines
2021:9
eldridge.cam
1 year ago
0ee1dcc0
26a7ae13
+47
2 changed files
expand all
collapse all
unified
split
2021
9
p1.hs
p2.hs
+18
2021/9/p1.hs
···
1
1
+
import Data.Array.Unboxed
2
2
+
import Data.Char
3
3
+
import Data.Maybe
4
4
+
5
5
+
readGrid :: String -> Array (Int, Int) Int
6
6
+
readGrid contents = listArray ((1, 1), (height, width)) $ concat input
7
7
+
where
8
8
+
input = fmap (fmap digitToInt) $ lines contents
9
9
+
width = length $ input !! 0
10
10
+
height = length input
11
11
+
12
12
+
neighbours (y, x) = [(y - 1, x), (y + 1, x), (y, x + 1), (y, x - 1)]
13
13
+
14
14
+
isMinPoint grid here = all (> (grid ! here)) $ mapMaybe (grid !?) (neighbours here)
15
15
+
16
16
+
answer grid = sum $ fmap ((+ 1) . (grid !)) $ filter (isMinPoint grid) $ indices grid
17
17
+
18
18
+
main = getContents >>= print . answer . readGrid
+29
2021/9/p2.hs
···
1
1
+
import Data.Array.Unboxed
2
2
+
import Data.Char
3
3
+
import Data.Maybe
4
4
+
import Data.List (sortBy)
5
5
+
import Data.Set qualified as Set
6
6
+
7
7
+
readGrid :: String -> Array (Int, Int) Int
8
8
+
readGrid contents = listArray ((1, 1), (height, width)) $ concat input
9
9
+
where
10
10
+
input = fmap (fmap digitToInt) $ lines contents
11
11
+
width = length $ input !! 0
12
12
+
height = length input
13
13
+
14
14
+
neighbours (y, x) = [(y - 1, x), (y + 1, x), (y, x + 1), (y, x - 1)]
15
15
+
16
16
+
isMinPoint grid here = all (> (grid ! here)) $ mapMaybe (grid !?) (neighbours here)
17
17
+
18
18
+
basin grid origin = basin_ Set.empty origin
19
19
+
where
20
20
+
basin_ :: Set.Set (Int, Int) -> (Int, Int) -> Set.Set (Int, Int)
21
21
+
basin_ co here
22
22
+
| not $ inRange (bounds grid) here = co
23
23
+
| grid ! here == 9 = co
24
24
+
| Set.member here co = co
25
25
+
| otherwise = foldl basin_ (Set.insert here co) (neighbours here)
26
26
+
27
27
+
answer grid = product $ take 3 $ sortBy (flip compare) $ fmap (Set.size . basin grid) $ filter (isMinPoint grid) $ indices grid
28
28
+
29
29
+
main = getContents >>= print . answer . readGrid