aboutsummaryrefslogtreecommitdiffstats
path: root/day8/solution.nim
diff options
context:
space:
mode:
Diffstat (limited to 'day8/solution.nim')
-rw-r--r--day8/solution.nim85
1 files changed, 85 insertions, 0 deletions
diff --git a/day8/solution.nim b/day8/solution.nim
new file mode 100644
index 0000000..f2c4f23
--- /dev/null
+++ b/day8/solution.nim
@@ -0,0 +1,85 @@
1import std/strutils
2import std/strformat
3import std/sequtils
4import std/algorithm
5import std/sugar
6
7type
8 Tree = tuple
9 height: int
10 found: bool
11
12proc scanTree(tree: Tree, answer: var int, maxHeight: var int): Tree =
13 result = tree
14 if tree.height > maxHeight:
15 maxHeight = tree.height
16 if not tree.found:
17 answer += 1
18 result = (tree.height, true)
19
20proc calculate(row: var seq[Tree], reved = false): int =
21 var
22 answer = 0
23 maxHeight = -1
24 newRow: seq[Tree]
25
26 if reved:
27 newRow = row.reversed()
28 else:
29 newRow = row
30
31 for i, r in newRow:
32 newRow[i] = scanTree(r, answer, maxHeight)
33 row = newRow
34
35 return answer
36
37func part1(content: seq[string]): int =
38 var grid = map(
39 content,
40 (row) => zip(map(row, (c) => ord(c) - ord('0')), newSeq[bool](row.len()))
41 )
42 var answer = 0
43
44 for row in grid.mitems():
45 answer += calculate(row)
46 answer += calculate(row, true)
47
48 for i in 0 ..< grid.len():
49 var col = map(grid, (row) => row[i])
50 answer += calculate(col)
51 answer += calculate(col, true)
52
53 return answer
54
55func checkVisibility(line: seq[int], height: int): int =
56 result = 0
57 for h in line:
58 result += 1
59 if h >= height:
60 return result
61
62 return result
63
64proc part2(content: seq[string]): int =
65 let grid = map(content, (row) => map(row, (c) => ord(c) - ord('0')))
66 result = 0
67
68 for i, row in grid:
69 for j, h in row:
70 var col = map(grid, (row) => row[j])
71 var count =
72 checkVisibility(row[j+1 .. ^1], h) *
73 checkVisibility(row[0 .. j-1].reversed(), h) *
74 checkVisibility(col[i+1 .. ^1], h) *
75 checkVisibility(col[0 .. i-1].reversed(), h)
76
77 # echo fmt"{i}, {j} = {count}"
78 result = max(result, count)
79
80 return result
81
82let content = readFile("./input.txt").strip().splitLines()
83
84echo part1(content)
85echo part2(content)