Go Back   Java Programming Forums > Java Standard Edition Programming Help > Algorithms & Recursion


Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 29-07-2010, 06:50 PM
Junior Member
 

Join Date: Jul 2010
Posts: 11
Thanks: 0
Thanked 0 Times in 0 Posts
b_jones10634 is on a distinguished road
Default Help; algorithm to determine 'range'

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:

Java 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.



Reply With Quote Share this thread on Facebook
Sponsored Links
Java Training from DevelopIntelligence
  #2 (permalink)  
Old 29-07-2010, 07:09 PM
helloworld922's Avatar
Super Moderator
 

Join Date: Jun 2009
Posts: 1,342
Thanks: 5
Thanked 284 Times in 256 Posts
helloworld922 will become famous soon enoughhelloworld922 will become famous soon enoughhelloworld922 will become famous soon enough
Default Re: Help; algorithm to determine 'range'

simple algorithm:

Pseudo Code:
startOfCurrentRange = list[0]
lastNumber = startOfCurrentRange - 1
rangeString = startOfCurrentRange + "-"
for every number in the list:
    if number != lastNumber + 1:
        the next number is not continuous
        rangeString += lastNumber
        rangeString += ", " + number + "-"
    end if
    lastNumber = number
end for
remove last character of rangeString (it's an extra "-")

One note: You'll need to determine what the behavior should be if you have two equal numbers in the list (if this input is allowed). For example: {1, 2, 3, 3}
__________________
ASCII a question .. Get an ANSI

Please surround your code with [highlight=Java]code goes here[/highlight].
Reply With Quote
  #3 (permalink)  
Old 30-07-2010, 06:05 PM
Junior Member
 

Join Date: Jul 2010
Posts: 11
Thanks: 0
Thanked 0 Times in 0 Posts
b_jones10634 is on a distinguished road
Default Re: Help; algorithm to determine 'range'

Thanks for your reply, unfortunately the algorithm you supplied does not account for all scenarios (it assumes that it will always start with a range, but what if the set is [6, 8, 10, 14, 18]).

And, FYI, for the scope of my project, the list of integers will NEVER have duplicate values.
Reply With Quote
  #4 (permalink)  
Old 30-07-2010, 06:41 PM
Junior Member
 

Join Date: Jul 2010
Posts: 11
Thanks: 0
Thanked 0 Times in 0 Posts
b_jones10634 is on a distinguished road
Default Re: Help; algorithm to determine 'range'

I think I've developed an algorithm that accounts for all necessary scenarios.
Any comments are welcomed.

Java Code:
int startOfCurrentRange = channelNums.get( 0 ).intValue();
int lastNumber = startOfCurrentRange - 1;
String channelRange = startOfCurrentRange + "-";
for( int i = 0; i < channelNums.size(); i++ )
{
                   
    int currentNumber = channelNums.get( i ).intValue();
    if( currentNumber != (lastNumber + 1) )
    {
        if( channelRange.charAt( channelRange.length() - 1 ) == '-' )
            channelRange = channelRange.substring( 0, channelRange.length() - 1 );
                       
        if( Integer.parseInt( Character.toString( channelRange.charAt( channelRange.length() - 1 ) ) ) == lastNumber )
            channelRange += ", " + currentNumber + "-";
        else
            channelRange += "-" + lastNumber + ", " + currentNumber + "-";
    }
                   
    if( i == channelNums.size() -1 )
        channelRange += currentNumber;
                   
    lastNumber = currentNumber;
}
               
// Remove trailing '-'
if( channelRange.charAt( channelRange.length() - 1 ) == '-' )
    channelRange = channelRange.substring( 0, channelRange.length() - 1 );
               
// Remove trailing single channel range (ex. replace traling '12-12' with '12')
if( channelRange.substring( (channelRange.length() - (Integer.toString( lastNumber ).length() * 2 + 1)), channelRange.length() )
    .compareToIgnoreCase( Integer.toString( lastNumber ) + "-" + Integer.toString( lastNumber ) ) == 0 )
        channelRange = channelRange.substring( 0, (channelRange.length() - (Integer.toString( lastNumber ).length() * 2 + 1)) ) +
            lastNumber;
Reply With Quote
  #5 (permalink)  
Old 30-07-2010, 07:13 PM
Junior Member
 

Join Date: Jul 2010
Posts: 6
Thanks: 0
Thanked 0 Times in 0 Posts
mcmillhj is on a distinguished road
Default Re: Help; algorithm to determine 'range'

I wrote this one, I think mine is a little simpler than yours. Let me know what you think.

Java Code
public class TestRange
{
	public static void main(String[] args)
	{
		int[] intArray = {2,3,4,7,9,10,11,15,16,19};
		String rangeString = "";
		
		//first element in the array
		int last = intArray[0];
		int current = 0;
		int rangeStart = -1;
		
		for(int i = 1; i <= intArray.length - 1; i++)
		{
			//assign the current number
			current = intArray[i];
			
			//test for range
			if ( current != (last+1) )
			{
				//if there is a range append it to the rangeString
				if(rangeStart != -1)
				{
					rangeString +=  rangeStart + "-" + last + ", ";
					
					//reset the range start variable
					rangeStart = -1;
				}
				else //if there isnt a range add the individual int to the rangeString
				{
					rangeString += last + ", ";
				}
				
				if( i == (intArray.length-1))
					rangeString += current;
			}
			else
			{
				//if there are consecutive numbers, store the starting number
				if( rangeStart == -1)
					rangeStart = last;
				
				//if this is the last element append any remaining ranges
				if( i == (intArray.length-1))
					rangeString +=rangeStart + "-" + last;
			}
			//assign the new last variable
			last = current;
		}
		
		//print rangeString
		System.out.println("rangeString: " + rangeString);
	}
}
This was my output:
rangeString: 2-4, 7, 9-11, 15-16, 19

Hunter
Reply With Quote
  #6 (permalink)  
Old 30-07-2010, 07:33 PM
Junior Member
 

Join Date: Jul 2010
Posts: 11
Thanks: 0
Thanked 0 Times in 0 Posts
b_jones10634 is on a distinguished road
Default Re: Help; algorithm to determine 'range'

Hey Hunter,

Thanks for your input, your solution does seem slightly less convoluted. I wasn't particular happy with my solution based on all the string comparisons and substrings.

I think I'll give yours a go and see how it works out.

Thanks again.
Reply With Quote
  #7 (permalink)  
Old 30-07-2010, 10:31 PM
helloworld922's Avatar
Super Moderator
 

Join Date: Jun 2009
Posts: 1,342
Thanks: 5
Thanked 284 Times in 256 Posts
helloworld922 will become famous soon enoughhelloworld922 will become famous soon enoughhelloworld922 will become famous soon enough
Default Re: Help; algorithm to determine 'range'

it's easy to find the start of the range: it's the smallest number in the list, and since you're list is already sorted, it's always going to be the very first element of the list (as indicated by the first line of the pseudo-code).
__________________
ASCII a question .. Get an ANSI

Please surround your code with [highlight=Java]code goes here[/highlight].
Reply With Quote
  #8 (permalink)  
Old 03-08-2010, 01:49 PM
Junior Member
 

Join Date: Jul 2010
Posts: 11
Thanks: 0
Thanked 0 Times in 0 Posts
b_jones10634 is on a distinguished road
Default Re: Help; algorithm to determine 'range'

HelloWorld,

Thanks for your reply, but I'm not sure you understood the problem at hand.

The task is not to find the start of the range... yes that is very easy to accomplish.
The task is to find the range of values in the given list. Your pseudo code attempts to satisfy this problem, but does not account for all scenarios.

For instance, your pseudo code algorithm assumes that the list of numbers will always start with a range of values (ex. [1, 2, 4, 5, 8]), but one of the most simples cases may incorporate a series that does NOT start with a range (ex. [1, 4, 5, 6, 9]).

A more suitable approach is to utilize the method either Hunter or I developed.

Further more, Hunter, your algorithm is very straight forward, however I found one small problem. The last range in the value is alwas 1 LESS than the actual value. For instance, if the series is [1, 2, 3, 4, 5], your algorithm will produce the range string = "1-4".
Reply With Quote
  #9 (permalink)  
Old 03-08-2010, 02:02 PM
Junior Member
 

Join Date: Jul 2010
Posts: 11
Thanks: 0
Thanked 0 Times in 0 Posts
b_jones10634 is on a distinguished road
Default Re: Help; algorithm to determine 'range'

Hunter,

Changing one line in your algoritm produces the correct result

Change this line:

Java Code
rangeString += rangeStart + "-" + previousNum;
to this:

Java Code
rangeString += rangeStart + "-" + currentNum;
Reply With Quote
  #10 (permalink)  
Old 04-08-2010, 05:58 PM
Junior Member
 

Join Date: Jul 2010
Posts: 6
Thanks: 0
Thanked 0 Times in 0 Posts
mcmillhj is on a distinguished road
Default Re: Help; algorithm to determine 'range'

When I make the change you suggest my algorithm actually does not work.

with this input and your suggested change: {2,3,4,9,11,12,13,16,19,19}

I get this output:

Java Code
rangeString: 2-9, 9, 11-16, 16, 19, 19
With no changes I get this (which is correct):

Java Code
rangeString: 2-4, 9, 11-13, 16, 19, 19
What kind of errors were you getting with my solution?

Hunter
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



Similar Threads
Thread Thread Starter Forum Replies Last Post
Q:BackTracking Algorithm Cross`17 Algorithms & Recursion 0 18-04-2010 04:33 AM
Genetic algorithm rpsaranya Algorithms & Recursion 2 06-03-2010 03:00 AM
set the slider's models (range) chronoz13 AWT / Java Swing 1 29-11-2009 03:59 AM
I have algorithm problem Newoor What's Wrong With My Code? 3 12-11-2009 12:11 AM
algorithm AmmrO Algorithms & Recursion 13 25-09-2009 02:18 AM


100 most searched terms
Search Cloud
2d arraylist java actionlistener actionlistener in java actionlistener java addactionlistener addactionlistener in java addactionlistener java applications of oops could not create java virtual machine xp double format java double to int java double to integer in java double to integer java eclipse shortcut keys eclipse tutorial for beginners exception in thread "awt-eventqueue-0" java.lang.outofmemoryerror: java heap space exception in thread "main" java.lang.nullpointerexception exception in thread "main" java.lang.outofmemoryerror: java heap space format double java get mouse position java http://www.javaprogrammingforums.com/object-oriented-programming/3713-limiting-decimal-places-double.html java 2d arraylist java actionlistener java addactionlistener java double format java double to int java double to integer java format double java forum java forums java get mouse position java list to map java mouse position java programmers forum java programming forum java programming forums java programming help java project ideas java sendkeys java two dimensional arraylist java.lang.classformaterror: truncated class file java.lang.outofmemoryerror: java heap space java.util.arraylist jbutton actionlistener jtextarea font jtextarea font color jtextfield font size jxl.read.biff.biffexception: unable to recognize ole stream two dimensional arraylist java writing ipod apps

All times are GMT. The time now is 11:59 PM.
Powered by vBulletin® Copyright ©2000-2009, Jelsoft Enterprises Ltd.