Hey, so I have an assignment for java using the hailstone sequence. My teacher wants us to print out the length of the longest sequence and the number for that. The problem I'm having is that I need to print out the actual sequence underneath the first part. Can anyone please help me?

import java.util.Scanner;

public class Hailstone
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        int first, last, counter = -500, highestSequence = 0, highestNumber = 0, number = 0, sequence = 0;

        System.out.println("First candidate?");
        first = scan.nextInt();

        System.out.println("Last candidate?");
        last = scan.nextInt();

            for(int x = first; x <= last; x++)
            {
                number = x;
                counter = 1;

                while(number !=1)
                {
                    if(number % 2 == 0) //even
                    {
                        number = number/2;
                    }
                    else //odd
                    {
                        number = number*3 + 1;
                    }

                counter++; //counts sequence
                }
                if(counter > highestSequence)
                {
                    highestSequence = counter;
                    highestNumber = x;

                    sequence = number; 
                }

            }
            System.out.println("longest sequence of " + highestSequence + " occurs at " + highestNumber);
        }
    }

How many sequences are you supposed to prompt for? You probably need a while loop.

You could probably use two Vectors or ArrayLists. One holds the longest list of numbers in the sequence and the other the current list of numbers in the sequence. If the current list of numbers is longer than the previous one, set the longest list = to the current list.

It's so easy to re-generate the sequence given the starting number, so I wouldn't bother trying to store sequences. Just write a trivial displaySequence(int startingNumber) method - it's just the loop/if from lines 21-30 with a print statement in the loop. Then just call that passing highestNumber.
If you are going to search a large number of starting values then this has the additional advantage of minimising the overhead during the search, so you can search more numbers in the same time.

Edited 2 Years Ago by JamesCherrill

This article has been dead for over six months. Start a new discussion instead.