Problem 11 on Project Euler involves calculating the maximum product of adjacent numbers in any direction in a 20×20 matrix.
The solution below takes advantage of the symmetry of calculations to cut down on unnecessary loop operations:
problem11 < - function() { numbers <- scan("problem11.dat") m <- matrix(as.numeric(numbers), 20, byrow=TRUE) maxprd <- 0 N <- 20; n <- 4 prd1 <- 0; prd2 <- 0; prd3 <- 0 dims <- dim(m) a <- (n-1) x <- c(0:a) for (i in 1:(dims[1])) { for (j in 1:(dims[2])) { prd1 <- ifelse(j <= N-a, prod(m[i,j+x]), 0) # row prod prd2 <- ifelse(i <= N-a, prod(m[i+x,j]), 0) # column prod # lower right diagonal prd3 <- ifelse(i <= N-a && j <= N-a, prod(diag(m[i:(i+a),j:(j+a)])),0) # lower left diagonal prd4 <- ifelse(i <= N-a && j > a, prod(diag(m[i:(i+a),j:(j-a)])), 0) maxprd < - max(prd1,prd2,prd3,prd4,maxprd) } } maxprd }