-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
82 lines (68 loc) · 2.21 KB
/
index.ts
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
import $ from '../../helpers'
export const countVisibleTrees = (rows: string[]) => {
const grid = $.Grid.fromRows(rows)
return grid.filter((tree, [ri, ci]) => {
const isLower = (t: string) => +t < +tree
// Edge check
if (ri === 0 || ci === 0) return true
if (ri === grid.height - 1 || ci === grid.width - 1) return true
// Left/right check
if (grid.row(ri).slice(0, ci).every(isLower)) return true
if (
grid
.row(ri)
.slice(ci + 1)
.every(isLower)
)
return true
// Top/bottom check
if (grid.column(ci).slice(0, ri).every(isLower)) return true
if (
grid
.column(ci)
.slice(ri + 1)
.every(isLower)
)
return true
return false
}).length
}
export const getHighestScenicScore = (rows: string[]) => {
const grid = $.Grid.fromRows(rows)
return Math.max(
...grid.flatMap((tree, [ri, ci]) => {
// Edge shortcut
if (ri === 0 || ci === 0) return 0
if (ri === grid.height - 1 || ci === grid.width - 1) return 0
let top = 0
let right = 0
let bottom = 0
let left = 0
// Start from the previous row and move up until the edge or finding a
// tree which is as tall or taller than the current tree.
for (let row = ri - 1; row >= 0; row--) {
top++
if (grid.get([row, ci]) >= tree) break
}
// Start from the next column and move right until the edge or finding a
// tree which is as tall or taller than the current tree.
for (let col = ci + 1; col < grid.width; col++) {
right++
if (grid.get([ri, col]) >= tree) break
}
// Start from the next row and move down until the edge or finding a tree
// which is as tall or taller than the current tree.
for (let row = ri + 1; row < grid.height; row++) {
bottom++
if (grid.get([row, ci]) >= tree) break
}
// Start from the previous column and move left until the edge or finding
// a tree which is as tall or taller than the current tree.
for (let col = ci - 1; col >= 0; col--) {
left++
if (grid.get([ri, col]) >= tree) break
}
return top * right * bottom * left
})
)
}