-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp11.hs
59 lines (52 loc) · 2.83 KB
/
p11.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
bestDown :: [[Integer]] -> Integer
bestDown grid = let bd g i j best = if i > 16 then
if j >= 19 then best
else bd g 0 (j + 1) best
else let prod = (grid!!i)!!j
* (grid!!(i + 1))!!j
* (grid!!(i + 2))!!j
* (grid!!(i + 3))!!j
in bd g (i + 1) j (max best prod)
in bd grid 0 0 0
bestRight :: [[Integer]] -> Integer
bestRight grid = let bd g i j best = if j > 16 then
if i >= 19 then best
else bd g (i + 1) 0 best
else let row = grid!!i
prod = row!!j
* row!!(j + 1)
* row!!(j + 2)
* row!!(j + 3)
in bd g i (j + 1) (max best prod)
in bd grid 0 0 0
bestDiagDown :: [[Integer]] -> Integer
bestDiagDown grid = let bd g i j best = if j > 16 then
if i >= 16 then best
else bd g (i + 1) 0 best
else let prod = (grid!!i)!!j
* (grid!!(i + 1))!!(j + 1)
* (grid!!(i + 2))!!(j + 2)
* (grid!!(i + 3))!!(j + 3)
in bd g i (j + 1) (max best prod)
in bd grid 0 0 0
bestDiagUp :: [[Integer]] -> Integer
bestDiagUp grid = let bd g i j best = if j > 16 then
if i >= 19 then best
else bd g (i + 1) 0 best
else let prod = (grid!!i)!!j
* (grid!!(i - 1))!!(j + 1)
* (grid!!(i - 2))!!(j + 2)
* (grid!!(i - 3))!!(j + 3)
in bd g i (j + 1) (max best prod)
in bd grid 3 0 0
toNums :: [String] -> [[Integer]]
toNums [] = []
toNums (s:ss) = map read (words s) : toNums ss
bestOfAll :: [[Integer]] -> Integer
bestOfAll grid = maximum [bestDown grid, bestRight grid, bestDiagDown grid, bestDiagUp grid]
main = do
content <- readFile "assets/p11.txt"
let ls = lines content
nums = toNums ls
best = bestOfAll nums
return best