【问题标题】:Getting consecutive numbers without repetition获得连续的数字而不重复
【发布时间】:2025-12-26 10:50:07
【问题描述】:

从一个随机的数字序列{"1", "2", "3", "4", "5"}中,要求确定3个连续数字组出现的次数,表示, 已生成的次数基数 = c ("1", "2", "3", "4", "5") 以下任意组 {"123", "234", " 345" }。

# I undertand that I have generate a sample with 5 numbers
a<-c(sample(1:5,5))
a
#I generated the list, as you can see I didn't fix a seed because I know that in every single sequence I will have differents grupos of 3 consecutive numbers, so I should obtain something like this

b<-c(2,3,4,5,1) #this example gives me just one that it would be {2,3,4}
b
#answer expected
1
#Then, I don't know how to obtain the sequence I have tried with permutations and combinations but I don't get it.

【问题讨论】:

  • 你计算重叠的组吗?如果你有一个序列 1、2、3、4、5,你会数出 123、234、345 吗?还是只有 1 个 123?
  • {2,4,5} 不连续。它们只是在增加。你想要哪个,连续的还是增加的?
  • “连续”是否包括环绕? 451, 512?

标签: r random numbers


【解决方案1】:

这将计算任何出现的三项连续增长(例如 123)。

countsequence <- function(x){
  if (length(x)<3){
    return(0)
  }
  count <- 0
  for(i in 3:length(x)){
    if(x[i-1]==x[i]-1 && x[i-2] == x[i]-2){
      count <- count + 1
    }
  }
  return(count)
} 

countsequence(1:5)
countsequence(c(2, 3, 4, 1, 5))

【讨论】:

  • 如果要连续且不递增,使用if语句如下:if(x[i-1]&lt; x[i] &amp;&amp; x[i-2] &lt; x[i-1]){
【解决方案2】:

参数k 用于子序列长度(在您的情况下为 3):

f <- function(b, k = 3){

  if(k > length(b)) return(0)
  
  check_list <- lapply(k:length(b), function(x) all(diff(b[(x-k+1):x]) == 1)) 
  sum(unlist(check_list))
}

如果您想计算增加或减少的子序列,请将 ==1 替换为适当的关系和数字。

【讨论】: