Sunday, January 25, 2015

Find If Array Elements Are Consecutive

Finding if the array elements are consecutive in terms of values in the array.
 {100,101,102} elements in the array are consecutive because of 100,101,102
{5, 2, 3, 1, 4,0,-1} elements in the array are consecutive because of -1,0,1,2,3,4,5

Finding total number of elements in a array of consecutive elements is
maximum element value - minimum element value + 1, i.e.
n= (max - min) + 1.

or 
sumofvalues = numberofelements*(min+max)/2;

303 = 3 * (100+102)/2

If the first condition matches we can check for avoiding other cases of repeating or not appearing elements.

No comments:

Post a Comment