Given a grid - what is the greatest product of four adjacent numbers in the same direction (up,down,left,right, all diagonals)
Setting up input (not shown)
Matricer for subsetting the matrix
horis <- cbind(x = 0, y = 0:3)
verti <- cbind(x = 0:3, y = 0)
right <- cbind(x = 0:3, y = 0:3)
left <- cbind(x = -(0:3), y = 0:3)
Beginning at a given position in the matrix, calculate the maximum product in different directions. We do not need all of them - they will be covered if we begin at another position.
ny_max_prod <- function(i,j){
position <- cbind(x = rep(i, 4), y =rep(j, 4))
liste <- list(position + horis, position - horis,
position +verti, position - verti,
position + right, position- right,
position + left, position - left)
liste <- liste[sapply(liste, function(mat) all(mat > 0))]
liste <- liste[sapply(liste, function(mat) all(mat < 21))]
mapply(function(x) grid[x], liste) %>%
apply(2, prod) %>%
max()
}
Apply that function to every position in the grid.
answer <- expand.grid(x = 1:20, y = 1:20) %>%
rowwise() %>%
mutate(maks = map2(x,y, ny_max_prod)) %>%
pull(maks) %>%
unlist() %>%
max()