Logo

Programming-Idioms

  • JS
  • Ruby
  • Python
  • Go

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.

import random
rand = random.Random()

the constructor uses the current time if used without arguments.
you could also use the functions of the random module (they are using a shared ``Random`` object which is constructed the first time random is imported
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.
Random.new

Don't use time for seeding. Just use the initializer without any arguments.
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...