Logo

Programming-Idioms

  • Pascal
  • Java

Idiom #69 Seed random generator

Use seed s to initialize a random generator.

If s is constant, the generator output will be the same each time the program runs. If s is based on the current value of the system clock, the generator output will be different each time.

import java.util.Random;
Random r = new Random(s);

s is of type long.
var
  SomeInteger: Integer;
  Value: double;
begin
  ...
   //initializes the PRNG's seed with a value depensing on system time
  Randomize; 
  Value := random;
  ...
   //Output will be the same eacht time the program runs
  RandSeed := SomeInteger; 
  Value := random;
...
end.
with Ada.Numerics.Discrete_Random;
declare
   Package Rand is new Ada.Numerics.Discrete_Random (Integer);
   Gen : Rand.Generator;
begin
   Rand.Reset (Gen, Initiator => S);
end;

You can also Save the state of the generator and Reset with that state later to continue the (pseudo-random) sequence.

New implementation...