Hello community,

I'm trying to develop a function to determine the 'range' of some integer values. 'Range' is the best way I can describe it, but it is different than the mathematical 'range', which is simply the absolute of the highest value minus the absolute of the lowest value.

It's best to describe with an example.

Lets say I have a list of Integers (pre sorted), containing values [2, 3, 4, 7, 8, 9, 14, 16, 18, 19, 20].

I need to build a string that describes the 'ranges' found within these values. So, for the above list of integers, the corresponding 'range' string would be "2-4, 7-9, 14, 16, 18-20".

I spent the afternoon here trying to create a function that would accomodate this requirement, but I can't seem to develop it in a way that will acount for all possible scenarios.

Following is my (not quite working) code:

Collections.sort( channelNums );
String channelRange = "";
int previousNum = 0;
boolean x = false;
 
for( int i = 0; i < channelNums.size(); i++ )
{
	int currentNum = channelNums.get( i ).intValue();
 
	if( i == 0 )
		channelRange = Integer.toString( currentNum );
	else
	{
		if( currentNum == (previousNum + 1) )
		{
			x = true;
			if( !channelRange.endsWith( "-" ) )
				channelRange += "-";
		}
		else
			channelRange += ", " + Integer.toString( currentNum );
	}
 
	previousNum = currentNum;
}
 
if( x )
	channelRange += Integer.toString( previousNum );

Any input would be highly appreciated. Thanks in advance.