获取连续数字而不重复
Getting consecutive numbers without repetition
从一个随机数字序列 {"1", "2", "3", "4", "5"} 中,要求确定 3 个连续数字组出现的次数,这意味着,使用 base = 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.
这将统计出现的三项连续增加的次数(例如 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))
参数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
。
从一个随机数字序列 {"1", "2", "3", "4", "5"} 中,要求确定 3 个连续数字组出现的次数,这意味着,使用 base = 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.
这将统计出现的三项连续增加的次数(例如 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))
参数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
。