# Euler 11

I’m beginning to like R. You can capture table data from a connection (a generalised file), one of which is the clipboard, to a data frame.

``````problem.matrix <-
``````

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 <-
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.

Consider that 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.

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