package rpi.goldsd.container;

import java.util.Enumeration;

/**
 * The <tt>RandomIntSequence</tt> class implements the <tt>Sequence</tt>
 * interface by providing a <tt>sequence()</tt> method that generates an
 * enumeration of <tt>Int</tt> objects using a linear congruential method.
 * This is not a very useful class, but rather an "excursion" as part of this
 * project.
 *
 * @see Sequence
 * @version 1.0, 4/16/98
 * @author David Goldschmidt
 */
public class RandomIntSequence implements Sequence
{
  /**
   * Returns an enumeration of pseudo-random integer values using
   * the linear congruential method with a default value of 25 as the
   * <i>seed</i> value.  The <tt>hasMoreElements()</tt> method of the
   * enumeration always returns <tt>true</tt> since the
   * <tt>nextElement()</tt> method will always return the next <tt>Int</tt>
   * object in the sequence.
   * @return an enumeration of pseudo-random <tt>Int</tt> objects.
   * @exception IllegalArgumentException if the <tt>startValue</tt> argument
   *                                     is not of type <tt>Int</tt>.
   */
  public Enumeration sequence()  { return sequence( new Int( 25 ) ); }


  /**
   * Returns an enumeration of pseudo-random integer values using the
   * given <i>seed</i> value <tt>s</tt>.
   * @param s the <i>seed</i> of the generated pseudo-random sequence.
   * @return an enumeration of pseudo-random integer values using the
   *         given <i>seed</i> value <tt>s</tt>.
   */
  public Enumeration sequence( int s )  { return sequence( new Int( s ) ); }


  /**
   * Returns an enumeration of pseudo-random integer values using
   * the linear congruential method.  The <tt>hasMoreElements()</tt>
   * method of the enumeration always returns <tt>true</tt> since the
   * <tt>nextElement()</tt> method will always return the next <tt>Int</tt>
   * object in the sequence.
   * @param startValue the <i>seed</i> value used to begin the linear
   *                   congruential process.
   * @return an enumeration of pseudo-random <tt>Int</tt> objects.
   * @exception IllegalArgumentException if the <tt>startValue</tt> argument
   *                                     is not of type <tt>Int</tt>.
   */
  public Enumeration sequence( final Object startValue )
    throws IllegalArgumentException
  {
    if ( ! ( startValue instanceof Int ) ) throw
      new IllegalArgumentException( "Start value must be of type Int." );

    return ( new Enumeration() {
      private int k = 37;
      private int c = 87;
      private int m = 100;
      private int x = ((Int)startValue).value;
      public boolean hasMoreElements()  { return true; }
      public Object nextElement()
      {
        Int result = new Int(x);
        x = ( k * x + c ) % m;
        return result;
      }
    } );
  }
}

