home *** CD-ROM | disk | FTP | other *** search
/ io Programmo 21 / IOPROG_21.ISO / SOFT / JSL.ZIP / JSL20 / simula / random / RandomEngineJava.java < prev    next >
Encoding:
Java Source  |  1998-02-20  |  1.4 KB  |  59 lines

  1.  
  2. package simula.random;
  3.  
  4. import java.util.Random;
  5.  
  6. /**
  7.  * This is the simplest implementation of the abstract class RandomEngine:
  8.  * it is based on the existing pseudo-random java engine and is the basis
  9.  * of the other generators in the hierarchy. Note however that
  10.  * this generator and the java one draw different numbers on the same seed.
  11.  */
  12.  
  13. public class RandomEngineJava extends RandomEngine {
  14.  
  15.     private Random r;
  16.     private int ibytes = 0;
  17.  
  18.     private int idat;
  19.  
  20.  
  21.     //  Costruttori
  22.  
  23.     /**
  24.      * Creates a new random number generator. Its seed is initialized to a
  25.      * value based on the current time.
  26.       */
  27.     public RandomEngineJava() { r = new Random(); }
  28.     /**
  29.      * Creates a new random number generator using the given seed.
  30.      * @param seed The initial seed.
  31.      */
  32.     public RandomEngineJava(long seed) { r = new Random(seed); }
  33.     /** 
  34.      * Returns the next pseudo-random byte from this generator.
  35.      * @return the next pseudo-random byte from this generator.
  36.      */
  37.     public byte nextByte() {
  38.         // Takes an int from the engine and returns it one byte a time.
  39.         byte d;
  40.  
  41.         if (ibytes <= 0) {
  42.             idat = r.nextInt();
  43.             ibytes = 4;
  44.         }
  45.         d = (byte) idat;
  46.         idat >>= 8;
  47.         ibytes--;
  48.         return d;
  49.     }
  50.     /**
  51.      * Sets a new seed.
  52.      * @param seed New initial seed.
  53.      */
  54.     public void setSeed(long seed) {
  55.         super.setSeed();              // Notify change to superclass
  56.         r.setSeed(seed);
  57.         ibytes = 0;                   // Clears the buffer
  58.     }
  59. }