Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a vector contains n consecutive numbers

Tags:

r

Suppose that my vector numbers contains c(1,2,3,5,7,8), and I wish to find if it contains 3 consecutive numbers, which in this case, are 1,2,3.

numbers = c(1,2,3,5,7,8) difference = diff(numbers) //The difference output would be 1,1,2,2,1 

To verify that there are 3 consecutive integers in my numbers vector, I've tried the following with little reward.

rep(1,2)%in%difference  

The above code works in this case, but if my difference vector = (1,2,2,2,1), it would still return TRUE even though the "1"s are not consecutive.

like image 587
Bonnie Avatar asked Apr 20 '13 07:04

Bonnie


People also ask

How do you find n consecutive numbers?

Consecutive Numbers Formula The formula for adding 'n' consecutive numbers = [a + (a + 1) + (a + 2) + .... {a + (n-1)}]. So, the sum of 'n' consecutive numbers or sum of 'n' terms of AP (Arithmetic Progression) = (n/2) × (first number + last number). Even Consecutive Numbers Formula = 2n, 2n+2, 2n+4, 2n+6,…

How do you check if an array has consecutive numbers?

Method 1 (Use Sorting) 1) Sort all the elements. 2) Do a linear scan of the sorted array. If the difference between the current element and the next element is anything other than 1, then return false. If all differences are 1, then return true.


1 Answers

Using diff and rle, something like this should work:

result <- rle(diff(numbers)) any(result$lengths>=2 & result$values==1) # [1] TRUE 

In response to the comments below, my previous answer was specifically only testing for runs of length==3 excluding longer lengths. Changing the == to >= fixes this. It also works for runs involving negative numbers:

> numbers4 <- c(-2, -1, 0, 5, 7, 8) > result <- rle(diff(numbers4)) > any(result$lengths>=2 & result$values==1) [1] TRUE 
like image 101
thelatemail Avatar answered Sep 22 '22 10:09

thelatemail