Reputation: 15
From a random sequence of numbers {"1", "2", "3", "4", "5"}, it is asked to determine the number of times that groups of 3 consecutive numbers appear, it means, the number of times that have been generated with the base = c ("1", "2", "3", "4", "5") any of the following groups {"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.
Upvotes: 0
Views: 89
Reputation: 5232
Parameter k
is for subsequence length (in your case 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))
}
If you want to count increasing or decreasing subsequences replace ==
and 1
with appropriate relation and number.
Upvotes: 0
Reputation: 1080
This will count any occurrence of a three item increasing streak (e.g. 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))
Upvotes: 1