Home Page

Tips page

University Page

Programming

Debian & Linux

Some works

About me

Del.icio.us Bookmarks

BOINC Combined Statistics

Site Statistics

Contact me sending an e-mail (antispam defense activated)

debian

hacker emblem

blogger

GeoURL

View Sandro Tosi's profile on LinkedIn

This is my Google PageRank

Group up consecutive numbers in a list

Group up consecutive numbers in a list

 Sandro Tosi, 10 September 2006


As output from a command (webMethods scheduler output), I recieve a list of number (in this case hours and minutes) that could be really long, let's say every hour from 5 AM to 9 PM is a 17 items list, that could be grouped up into 5..21 .

The Java code provided does exactly this work: takes an int array as input and returns a StringBuffer with the sequential numbers grouped up as shown above.

Here is the main code (highlighted with java2html), the full source code is available at this link:

    //loop on hours; i it's the index of current element
    while (i<hours.length) {
//set it to current scanned element in hours current=hours[i]; //the next element index j=i+1; //This is the main hack: I fix the current element, hours[i], //then scan until elements are consecutive, incrementing j while (j<hours.length && current+j-i==hours[j]) { j++; }

//if j was not modified, than print only current if (j==i+1) {
output.append(separator+current);
separator=", ";
i=j;
//if it's modified, than print a set } else {
output.append(separator+current+".."+hours[j-1]);
separator=", ";
i=j;
}
}

Drop me an email, if you'd like to provide some comments.