Java: Ulam Sequence - Answer

A solution to the Ulam Sequence problem is written here as a class with static methods. One method computes and returns the sequence as a string, and the other returns it as an ArrayList.

Missing main and user interface. You need to write a main program and a user interface (eg, JOptionPane or GUI) to use these functions, or just copy the function into an existing program.

Note that the second function uses Java 5 features: autoboxing and generics.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54 
 55 
// flow-loops/ulam/UlamLogic.java - Compute Ulam sequence

import java.util.*;

/**
 * UlamLogic class.  This class could be used as the logic
 * for either a GUI or command-line user interface.
 * Note: computeUlamSequence() uses Java 5 features.
 * @version 2004-11-06
 * @author  Fred Swartz
 */
public class UlamLogic {
    /** Function which computes the Ulam sequence.
     *       A string value is only useful for display.
     *       Use the ArrayList version below for more utility.
     * @param n Starting number for Ulam sequence.
     * @return String of comma-separated values in sequence.
     */
    public static String computeUlamString(int n) {
        String result = "" + n;
        while (n > 1) {
            if (n%2 == 0) {  // if even
                n = n / 2;
            } else {         // if odd
                n = 3 * n + 1;
            }
            result = result + ", " + n;
        }
        return result;
    }//end computeUlamString
    
    
    /** Function which computes the Ulam sequence.
     *  The use of an ArrayList is more general than
     *  a string because the numbers can be used (eg, to find
     *  the maximum value ever reached), the number of
     *  elements in the sequence can easily be determined, etc.
     *  Note: Java 5 features (generics and autoboxing).
     * @param n Starting number for Ulam sequence.
     * @return ArrayList of the sequence values.
     */
    public static ArrayList<Integer> computeUlamSequence(int n) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        result.add(n);
        while (n > 1) {
            if (n%2 == 0) {  // if even
                n = n / 2;
            } else {         // if odd
                n = 3 * n + 1;
            }
            result.add(n);
        }
        return result;
    }//end computeUlamSequence
}