I've been learning R for the past few months and while trying to solve one of the challenges from Project Euler which asks me to find the thirteen adjacent digits in the 1000-digit number that have the greatest product. The number they provide has at least 1000 digits so I won't type it here, but you can find the problem here.
I've implemented a possible solution in R (v.4.3.1,OS: mingw32) that takes the number, converts it to a character string and splits it based on a certain parameter, then iterates through each sequence of 13 digits to find the product of each sequence until the greatest product of a sequence is found. However, I'm subsetting incorrectly, and I can't seem to figure out a solution.
I'm getting the following error when I execute the function:
Error in vec_pow[i:(i + 12)] : only 0's may be mixed with negative subscripts
Here's where the error occurs:
traceback()
1: maxprod_seq(1.23456789876543e+33)
> traceback(maxprod_seq(1.23456789876543e+33))
Error in vec_seq[i:(i + 12)] :
only 0's may be mixed with negative subscripts
In addition: Warning message:
In maxprod_seq(1.23456789876543e+33) : NAs introduced by coercion
Called from: maxprod_seq(1.23456789876543e+33)
Browse[1]> i
[1] -11
Browse[1]> split_seq
[1] "1" "." "2" "3" "4" "5" "6" "7" "8" "9" "8" "7" "6" "5" "4" "3" "e" "+" "3"
[20] "3"
Browse[1]> length(vec_seq)
[1] 20
Browse[1]> vec_seq
[1] 1 NA 2 3 4 5 6 7 8 9 8 7 6 5 4 3 NA NA 3 3
Here's my code:
maxprod_seq <- function(num){
split_seq <- strsplit(as.character(num), split ="")[[1]]
vec_seq <- as.numeric(split_seq)
max_prod <- 0
for(i in 1:length(vec_seq)-12){
prodct <- prod(vec_seq[i:(i+12)])
if(prodct > max_prod){
max_prod <- prodct
}
}
return(max_prod)
}
maxprod_seq("1234567898765432135765843356778877654334567788766554467788767685838292949595969694838284959595948838383849595959483838384959594")
I use sapply instead, and the function seems to be working properly.
maxprod_seq <- function(num) {
split_seq <- strsplit(as.character(num), split ="")[[1]]
vec_seq <- as.numeric(split_seq)
if (length(vec_seq) < 13) {
stop("Sequence must have at least 13 elements.")
}
products <- sapply(1:(length(vec_seq) - 12), function(i) prod(vec_seq[i:(i + 12)]))
max_prod <- max(products)
return(max_prod)
}
maxprod_seq("1234567898765432135765843356778877654334567788766554467788767685838292949595969694838284959595948838383849595959483838384959594")
maxprod_seq(that) [1] 6.1222e+10