library(readr)
Part 1
Input
<- as.matrix(read_fwf("input.txt",fwf_widths(widths = rep(1,99)))) input
Part 1
Code
<- function(x){
is_visible <- vector(mode = "logical", length = length(x))
results
for (i in seq_along(x)) {
if(i == 1 || i == length(x)){
<- TRUE
results[i] else if (all(x[i] > x[1:i-1]) || all(x[i] > x[(i+1):length(x)])) {
} <- TRUE
results[i] else {
} <- FALSE
results[i]
}
}
results
}
sum(t(apply(input, 1, is_visible)) | apply(input, 2, is_visible))
[1] 1840
Part 2
<- function(x){
scenic_score <- vector(mode = "numeric", length = length(x))
right <- vector(mode = "numeric", length = length(x))
left
for (i in seq_along(x)) {
if (i == 1) {
<- 0
left[i] else {
} <- which(x[(i-1):1] >= x[i])[1]
left_dist <- ifelse(is.na(left_dist), i-1, left_dist)
left[i]
}if(i==length(x)){
<- 0
right[i] else {
} <- which(x[(i+1):length(x)] >= x[i])[1]
right_dist <- ifelse(is.na(right_dist), length(x) - i, right_dist)
right[i]
}
}
*right
left
}
max(t(apply(input, 1, scenic_score)) * apply(input, 2, scenic_score))
[1] 405769