We expect this output: 21 trees visible (16 trees visible on the edge and 5 in the interior)
All of the trees around the edge of the grid are visible
The top-left 5 is visible from the left and top.
The top-middle 5 is visible from the top and right.
The top-right 1 is not visible from any direction.
The left-middle 5 is visible, but only from the right.
The center 3 is not visible from any direction; for it to be visible, there would need to be only trees of at most height 2 between it and an edge.
The right-middle 3 is visible from the right.
In the bottom row, the middle 5 is visible, but the 3 and 4 are not.
visible_vec <-function(line) { line %>%accumulate(max) %>%lag(default =-1)}is_visible <-function(line) { line >visible_vec(line)}test <-tribble(~line,"30373","255122","65332","33549","35390" ) %>%make_grid()test %>%group_by(col) %>%mutate(top =is_visible(value)) %>%group_by(row) %>%mutate(left =is_visible(value)) %>%filter(row ==2, col ==2)
# A tibble: 1 × 5
# Groups: row [1]
value col row top left
<int> <int> <int> <lgl> <lgl>
1 5 2 2 TRUE TRUE
test %>%group_by(col) %>%mutate(top =is_visible(value)) %>%group_by(row) %>%mutate(left =is_visible(value)) %>%mutate(right =rev(is_visible(rev(value)))) %>%filter(row ==2, col ==3)
# A tibble: 1 × 6
# Groups: row [1]
value col row top left right
<int> <int> <int> <lgl> <lgl> <lgl>
1 5 3 2 TRUE FALSE TRUE
test %>%group_by(col) %>%mutate(top =is_visible(value)) %>%mutate(bottom =rev(is_visible(rev(value)))) %>%group_by(row) %>%mutate(left =is_visible(value)) %>%mutate(right =rev(is_visible(rev(value)))) %>%filter(row ==4, col ==3)
# A tibble: 1 × 7
# Groups: row [1]
value col row top bottom left right
<int> <int> <int> <lgl> <lgl> <lgl> <lgl>
1 5 3 4 FALSE TRUE TRUE FALSE
The result: 1832
data %>%group_by(col) %>%mutate(top =is_visible(value)) %>%mutate(bottom =rev(is_visible(rev(value)))) %>%group_by(row) %>%mutate(left =is_visible(value)) %>%mutate(right =rev(is_visible(rev(value)))) %>%ungroup() %>%mutate(visible = top + bottom + left + right) %>%summarise(visible =sum(visible >0))
# A tibble: 1 × 1
visible
<int>
1 1832
Part 2: Consider each tree on your map. What is the highest scenic score possible for any tree?
In the example above, consider the middle 5 in the second row:
30373
25512
65332
33549
35390
Looking up, its view is not blocked; it can see 1 tree (of height 3).
Looking left, its view is blocked immediately; it can see only 1 tree (of height 5, right next to it).
Looking right, its view is not blocked; it can see 2 trees.
Looking down, its view is blocked eventually; it can see 2 trees (one of height 3, then the tree of height 5 that blocks its view).
A tree’s scenic score is found by multiplying together its viewing distance in each of the four directions. For this tree, this is 4 (found by multiplying 1 * 1 * 2 * 2).
I build helper functions to get the cell for each direction: