(This article was first published on

**The Devil is in the Data**, and kindly contributed to R-bloggers)## Euler Problem 11 Definition

In the 20×20 grid below, four numbers along a diagonal line have been marked in red.

The product of these numbers is 26 × 63 × 78 × 14 = 1,788,696. What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20 by 20 grid?

## Solution

The solution applies straightforward vector arithmetic. The product of all verticals is an array of the product of rows 1 to 4, rows 2 to 5 and so on. The code uses a similar logic for the horizontals and the diagonals.

#Read and convert data square <- readLines("Euler/p011_matrix.txt") square <- as.numeric(unlist(lapply(square, function(x){strsplit(x, " ")}))) square <- matrix(square, ncol=20) # Define products prod.vert <- square[1:17, ] * square[2:18, ] * square[3:19, ] * square[4:20, ] prod.hori <- square[,1:17] * square[,2:18] * square[,3:19] * square[,4:20] prod.dia1 <- square[1:17, 1:17] * square[2:18, 2:18] * square[3:19, 3:19] * square[4:20, 4:20] prod.dia2 <- square[4:20, 1:17] * square[3:19, 2:18] * square[2:18, 3:19] * square[1:17, 4:20] answer <- max(prod.vert, prod.hori, prod.dia1, prod.dia2)

The post Euler Problem 11: Largest Product in a Grid appeared first on The Devil is in the Data.

To

**leave a comment**for the author, please follow the link and comment on their blog:**The Devil is in the Data**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...