Logo

Programming-Idioms

  • PHP
  • Go
  • Js

Idiom #70 Use clock as random generator seed

Get the current datetime and provide it as a seed to a random generator. The generator sequence will be different at each run.

Math.random ()

Math.random uses the current time to generate a double floating point number from 0 to 1.
Repeated calls will give different outputs each time.
srand(time());

While this is correct, the PHP Manual entry for srand() states: "There is no need to seed the random number generator with srand() or mt_srand() as this is done automatically."
import "math/rand"
import "time"
r := rand.New(rand.NewSource(time.Now().UnixNano()))

r is of type *rand.Rand.
#include <stdlib.h>
#include <time.h>
srand((unsigned)time(0));

New implementation...
< >
deleplace