-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day08.idr
93 lines (74 loc) · 2.09 KB
/
Day08.idr
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
module Day08
import AocUtils
import Data.List1
import Data.Nat
import Data.Maybe
import Data.Morphisms
import Data.SortedMap
import Data.String
%default total
-- Parsing
Coord : Type
Coord = (Int, Int)
Input : Type
Input = SortedMap Coord Nat
parse : String -> Input
parse = fromList . (>>= parseLine) . zipWithIndex . lines
where
formPair : Nat -> (Nat, Char) -> (Coord, Nat)
formPair i (j, ch) = ((cast i, cast j), cast $ String.singleton ch)
parseLine : (Nat, String) -> List (Coord, Nat)
parseLine (i, str) = map (formPair i) $ zipWithIndex $ unpack str
-- Part 1
%hint
additive : Num a => Monoid a
additive = Additive
dirs : List Coord
dirs = [(0, -1), (0, 1), (-1, 0), (1, 0)]
covering
visible : Input -> Coord -> Bool
visible treeMap pos =
case lookup pos treeMap of
Nothing => False
Just height => any (visible' height pos) dirs
where
visible' : (height : Nat) -> (pos : Coord) -> (dir : Coord) -> Bool
visible' height pos dir =
let pos' = pos <+> dir in
case lookup pos' treeMap of
Nothing => True
Just h => height > h && visible' height pos' dir
covering
solve1 : Input -> Nat
solve1 treeMap = length $ filter (visible treeMap) $ keys treeMap
covering
part1 : Input ~> String
part1 = Mor $ ("Part 1: " ++) . show . solve1
-- Part 2
covering
viewingDistances : Input -> Coord -> List Nat
viewingDistances treeMap pos =
case lookup pos treeMap of
Nothing => []
Just height => map (distance 0 height pos) dirs
where
distance : Nat -> (height : Nat) -> (pos : Coord) -> (dir : Coord) -> Nat
distance acc height pos dir =
let pos' = pos <+> dir in
case lookup pos' treeMap of
Nothing => acc
Just h =>
if h >= height
then S acc
else distance (S acc) height pos' dir
covering
solve2 : Input -> Nat
solve2 treeMap =
max' $ (0 :::) $ map (product . viewingDistances treeMap) $ keys treeMap
covering
part2 : Input ~> String
part2 = Mor $ ("Part 2: " ++) . show . solve2
-- Plumbing
covering
main : IO ()
main = interact (unlines . (applyMor . sequence) [part1, part2] . parse)