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)

## ── Attaching core tidyverse packages ─────────────────────────────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.4     ✔ tidyr     1.3.1
## ✔ purrr     1.0.2     
## ── Conflicts ───────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the ]8;;http://conflicted.r-lib.org/conflicted package]8;; to force all conflicts to become errors

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()