August 6, 2021

Largest product in a grid

Euler problem 11 solution using R. You can capture table data from a connection (a generalised file), one of which is the clipboard, to a data frame.

problem.matrix <-
    as.matrix(read.table("clipboard",sep=" "))

This gives a 20×20 matrix. Awesome. Although this all goes askew once Visual Studio is involved – I added a text file containing the data to the solution explorer and discovered it gets encoded in some fantastic way introducing a Byte Order Mark (BOM) so I needed to specify the encoding scheme.

problem.matrix <-
    as.matrix(read.csv("euler.txt",
              header = FALSE,
              sep = " ",
              fileEncoding = "UTF-8-BOM"))

The problem is to find the greatest product of four adjacent numbers (horizontally, vertically or diagonally) in a 20×20 grid. I’m approaching this by considering the products of multiple matrices.

The solution cannot lie, for example, in the last 3 columns because we need 4 numbers. So let’s consider a 17×17 matrix being moved along and down the data.

Matrix Diagonal

Remember to repeat this from right to left as there are two diagonal directions. The same approach can be taken for the rows, using a 17×20 matrix and for the columns using a 20×17 matrix.

problem.matrix <-
    as.matrix(read.csv("euler.txt",
              header = FALSE,
              sep = " ",
              fileEncoding = "UTF-8-BOM"))

diagonal.ltor <-
    problem.matrix[1:17, 1:17] *
    problem.matrix[2:18, 2:18] *
    problem.matrix[3:19, 3:19] *
    problem.matrix[4:20, 4:20]

diagonal.rto1 <-
    problem.matrix[4:20, 1:17] *
    problem.matrix[3:19, 2:18] *
    problem.matrix[2:18, 3:19] *
    problem.matrix[1:17, 4:20]

horizontal <-
    problem.matrix[, 1:17] *
    problem.matrix[, 2:18] *
    problem.matrix[, 3:19] *
    problem.matrix[, 4:20]

vertical <-
    problem.matrix[1:17,] *
    problem.matrix[2:18,] *
    problem.matrix[3:19,] *
    problem.matrix[4:20,]

print(max(diagonal.ltor, diagonal.rto1, horizontal, vertical))

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close