Logo

Programming-Idioms

  • Go
  • PHP
  • Js

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.

const seed = require ('seedrandom')
seed (s)

s is impure—it can give different outputs with the same input.
import "math/rand"
r := rand.New(rand.NewSource(s))

s is of type int64.
r is of type *rand.Rand.
import "math/rand/v2"
r := rand.New(rand.NewPCG(s, s))

The PCG source has 128 bits of internal state, thus its constructor takes 2 uint64.
The two arguments would usually have a different value.
srand($s);
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...
programming-idioms.org