initialize with time seed array

pull/13966/head
Subhomoy Haldar 2022-04-07 16:47:27 +05:30
parent 79d5c87e47
commit cc77816682
1 changed files with 9 additions and 3 deletions

View File

@ -3,6 +3,8 @@
// that can be found in the LICENSE file.
module mt19937
import rand.seed
/*
C++ functions for MT19937, with initialization improved 2002/2/10.
Coded by Takuji Nishimura and Makoto Matsumoto.
@ -59,12 +61,18 @@ const (
// **NOTE**: The RNG is not seeded when instantiated so remember to seed it before use.
pub struct MT19937RNG {
mut:
state []u64 = []u64{len: mt19937.nn}
state []u64 = get_first_state(seed.time_seed_array(2))
mti int = mt19937.nn
bytes_left int
buffer u64
}
fn get_first_state(seed_data []u32) []u64 {
mut state := []u64{len: mt19937.nn}
calculate_state(seed_data, mut state)
return state
}
// calculate_state returns a random state array calculated from the `seed_data`.
fn calculate_state(seed_data []u32, mut state []u64) []u64 {
lo := u64(seed_data[0])
@ -83,8 +91,6 @@ pub fn (mut rng MT19937RNG) seed(seed_data []u32) {
eprintln('mt19937 needs only two 32bit integers as seed: [lower, higher]')
exit(1)
}
// calculate 2 times because MT19937RNG init didn't call calculate_state.
rng.state = calculate_state(seed_data, mut rng.state)
rng.state = calculate_state(seed_data, mut rng.state)
rng.mti = mt19937.nn
rng.bytes_left = 0