Chandu Chandu - 7 months ago 22
Java Question

Printing consecutive numbers

I have sorted integer array {1,2,3,7,9,24,25,26,78} and would like to print consecutive to print {1-3,7,9,24-26,78}. That is, every time there is a set of consecutive numbers occurring in the array, I would like to print out the range from the minimum number to the maximum number.

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Consecutive{

public static void main(String[] args){
int[] a={1,2,3,7,9,24,25,26,78};

for(int i=0;i<a.length;i++){
int count=0;
int first=0;

/* System.out.println(i);*/
first=a[i];

if(a[i+1]-a[i]==1){

count++;

int last=a[i]+count;
i++;
System.out.println(first + " " + last);

}else{


System.out.println(a[i]);

}

}
}
}

Answer

You could do something like this:

    if(a.length>0) {            
        int i=0,j=0; 
        do{
            j=i+1;
            while(j<a.length){
                if(a[j]-a[i]!=j-i)
                    break;
                j++;
            }
            if(i==j-1)
                System.out.println(a[i]);
            else
                System.out.println(a[i] + "-" + a[j-1]);
            i=j;
        }while(i<a.length);
    }

I hope it helps.

Comments