Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

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.

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;
#include <stdlib.h>
srand(s);
#include <stdlib.h>
srand(s);
using System;
var random = new Random(s);
std.random, std.stdio;
auto s = 8;
auto gen = Random(s);
writeln(gen.front);
import "dart:math";
var r = new Random(s);
:random.seed(s)
  call random_seed(size = n)
  allocate(seed(n))
  ! ...
  call random_seed(put=seed)
import "math/rand/v2"
r := rand.New(rand.NewPCG(s, s))
import "math/rand"
r := rand.New(rand.NewSource(s))
System.Random.mkStdGen s
const seed = require ('seedrandom')
seed (s)
import java.util.Random;
Random r = new Random(s);
val random = Random(seed=s)
call random_seed (put=s)
math.randomseed(s)
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.
srand($s);
import random
rand = random.Random(s)
r = Random.new(s)
use rand::{Rng, SeedableRng, rngs::StdRng};
let s = 32;
let mut rng = StdRng::seed_from_u64(s);

New implementation...
programming-idioms.org