r - 向量中特定序列的数量

标签 r recursion vector

给定两个向量:'pattern' 和 'trail'。问题:“轨迹”中“模式”出现的频率如何?
例子:

pattern <- c(1,2,3)

trail <- 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)
}
但是这个函数不会终止。当然,欢迎使用非递归解决方案。谢谢你的帮助!

最佳答案

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

关于r - 向量中特定序列的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55009592/

相关文章:

c++ - 在类中声明 vector 的大小

r - ggplot 重新排序分类变量

r - 计数与 R data.table foverlaps() 或 IRanges 的预期重叠

r - 更新一个观察者中的多个单选按钮仅适用于第一个单选按钮

javascript - 电话键盘按键的字母组合

java - 可变预期 java vector

r - 使用 ggplot aes_string、组和线型时出现的问题

java - 这段代码中的中序遍历有什么问题?

java - 如何不仅获取字符串的所有子字符串,还获取字符串的所有可能的子字符串?

c++ - set 是否有可能将 std::vector 作为存储其元素的底层存储?