I'm tryin to find the longest common sequence between two very long sequences, but it gives an error "C stack usage 15924368 is too close to the limit" Here is the code:
lcs <- function(X, Y, m, n, dp) {
if (m == 0 | n == 0) {
return(0)
}
if (dp[m, n] != -1) {
return(dp[m, n])
}
if (is.na(X[m]) == is.na(Y[n])) {
dp[m, n] <- 1 + lcs(X, Y, m - 1, n - 1, dp)
return(dp[m, n])
}
dp[m, n] <- max(lcs(X, Y, m, n - 1, dp), lcs(X, Y, m - 1, n, dp))
return(dp[m, n])
}
dp <- matrix(-1, nrow = nchar(a) + 1, ncol = nchar(b) + 1)
longcs= lcs(a, b, nchar(a), nchar(b), dp)
and also is there any way to see the string? This code shows only the number.
I guess it would be better to avoid using the recursion for LCS, since R seems to have some limitations on the depths of recursions, and recursions are slow sometimes (especially when you need to copy large arguments that would not result in a copy in an iterative implementation, see the comment from @Konrad Rudolph).
If you have relative short strings
XandYto find the LCS, probably you can try the code belowExample