R 不重复地获得连续的数字

R 不重复地获得连续的数字,r,random,numbers,R,Random,Numbers,根据随机数字序列{“1”、“2”、“3”、“4”、“5”},要求确定由3个连续数字组成的组出现的次数,这意味着,以基=c(“1”、“2”、“3”、“4”、“5”)生成的下列组{“123”、“234”、“345”}中任何一组的次数 #我知道我已经生成了一个包含5个数字的样本 a这将计算三项增加条纹的任何发生(例如123) countsequence参数k用于子序列长度(在您的案例3中): f长度(b))返回值(0) 检查列表是否计算重叠的组数?如果你有一个序列1,2,3,4,5,你会有一个1232

根据随机数字序列{“1”、“2”、“3”、“4”、“5”},要求确定由3个连续数字组成的组出现的次数,这意味着,以基=c(“1”、“2”、“3”、“4”、“5”)生成的下列组{“123”、“234”、“345”}中任何一组的次数

#我知道我已经生成了一个包含5个数字的样本

a这将计算三项增加条纹的任何发生(例如123)


countsequence参数
k
用于子序列长度(在您的案例3中):

f长度(b))返回值(0)

检查列表是否计算重叠的组数?如果你有一个序列1,2,3,4,5,你会有一个123234345的计数吗?或者只有1代表123?{2,4,5}不是连续的。它们只是在增加。您想要哪一个,连续还是递增?连续是否包括环绕?451512?如果它是连续的而不是递增的,则使用if语句如下:
if(x[i-1]
# 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.

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))
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))
}