Advent of Code 2021 - Day 9

Aloha, seems like we are stuck in a lava cave.

raw_data <- readLines(con = "day_nine")
integer_split <- lapply(raw_data, function(x){
  as.integer(strsplit(x, split = "")[[1]])
})

Part 1:

m <- do.call(rbind, integer_split)
#add NA
m_t <- cbind(NA, rbind(NA, m,  NA), NA)
#functions
MNeighbors <- function(mat, i = 2L, j = 3L) {
  all(mat[i, j] < c(mat[i, j - c(-1L, 1L)], mat[i - c(-1L, 1L), j]), na.rm = TRUE)
}
vMNeighbors <- Vectorize(FUN = MNeighbors, "j")
#get borders
rows <- 2L : (nrow(m_t) - 1L)
cols <- 2L : (ncol(m_t) - 1L)

mask <- lapply(rows, function(y) {
  vMNeighbors(m_t, i = y, j = cols)
})
mask <- do.call(rbind, mask)
(answer <- sum(m[mask] + 1))
## [1] 600

Part 2:

To be updatet

Avatar
Moritz Mueller-Navarra

A Data Scientist using R

Related