Logo

Programming-Idioms

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

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.

#include <stdlib.h>
#include <time.h>
srand((unsigned)time(0));
using System;
Random rng = new Random(DateTime.Now.Day);
import std.datetime, std.random;
auto rng = Random(cast(uint)Clock.currTime.stdTime);
import std.datetime, std.random;
rndGen.seed(cast(uint)Clock.currTime.stdTime);
var r = new Random(new DateTime.now().millisecondsSinceEpoch);
  call random_seed (size=k)
  allocate (seed(k))
  call date_and_time (values=val)
  seed = [(173*i**2+4567,i=1,k)]
  m = min(8,k)
  seed(1:m) = seed(1:m) + val(m:1:-1)
  call random_seed (put=seed)
import "math/rand"
import "time"
r := rand.New(rand.NewSource(time.Now().UnixNano()))
import System.Random
getStdGen
Math.random ()
import java.util.Random;
Random rand = new Random(System.currentTimeMillis());
(setf *random-state* (make-random-state t))
math.randomseed( os.time() )
srand(time());
Randomize;
srand time;
import random
rand = random.Random()
Random.new
use rand::{Rng, SeedableRng, rngs::StdRng};
use std::time::SystemTime;
let d = SystemTime::now()
    .duration_since(SystemTime::UNIX_EPOCH)
    .expect("Duration since UNIX_EPOCH failed");
let mut rng = StdRng::seed_from_u64(d.as_secs());

New implementation...
< >
deleplace