向量中特定序列的数量

Mic*_*227 4 recursion r vector

给定两个向量:“模式”和“尾随”。问题:“线索”中的“模式”多久出现一次?例:

模式<-c(1,2,3)

追踪<-c(7,1,4,2,9,2,3)

正确的解决方案:2(即1,2,3和1,2,3;“ 2”在中间出现两次)。

我试过了:

getPerformance <- function(pattern,trail) {
  tmp <- 0
  for(i in 1:length(pattern)) {
    for(j in 1:length(trail)) {
      if(pattern[i]==trail[j]) {

        if(i<length(pattern)) {
          sum(pattern[i:length(pattern)]) 
        }
        tmp <- 1 * getPerformance(pattern[i:length(pattern)],trail[j:length(trail)])
      }
    }
  }
  return(tmp)
}
Run Code Online (Sandbox Code Playgroud)

但是此功能不会终止。当然,欢迎使用非递归解决方案。谢谢你的帮助!

Gre*_*gor 7

n_subseq = function(trail, pattern) {
  # generate all subsets of the elements of `trail` in `pattern`
  # of `length(pattern)`
  # preserving order (as combn does)
  # that are all equal to `pattern`
  sum(combn(
    x = trail[trail %in% pattern],
    m = length(pattern),
    FUN = function(x) all(x == pattern)
  ))
}

n_subseq(trail = c(7, 1, 4, 2, 9, 2, 3), pattern = 1:3)
# [1] 2

n_subseq(c(1, 2, 2, 3, 3), 1:3)
# [1] 4
Run Code Online (Sandbox Code Playgroud)