Grouping an array of integers that skip numbers in Java

Say I have the following int array:

[1,2,3,6,7, 8, 9,20, 22]

I’d like to be able to display to the user the following based off the above array:

Numbers 1 through 3, 6 through 9, 20, 22

How could I go about doing this? Essentially checking if the number previous equals the current number – 1? Guess I just answered my own question, but any shortcuts/pointers would be welcome.

Note: only dealing with integers, nothing negative (wouldn’t be an integer would it).

Answer

A live example using Ideone can be found here. Runs in O(n) time.


Integer[] A = {1, 2, 3, 6, 7, 8, 9, 20, 22};
int start = 0, end;

System.out.print("Numbers ");                 
while((end = start) < A.length){
    // Increment the 'end' pointer while consecutive numbers exist.
    while(end + 1 < A.length && A[end + 1] == A[end] + 1) end++;

    // If end == start: 'A[start]'
    // Else           : 'A[start] through A[end]'
    System.out.print(A[start] + 
                     (end == start ? "":(" through " + A[end])) +  
                     (end < A.length - 1 ? ", ":""));

    // Increment start pointer to next element in A
    start = end + 1;
}

Leave a Reply

Your email address will not be published. Required fields are marked *