rand: rand_r(seed)

pull/2016/head
Nicolas Sauzede 2019-09-16 21:21:21 +02:00 committed by Alexander Medvednikov
parent 083d747302
commit ff009f1c4e
2 changed files with 43 additions and 1 deletions

View File

@ -13,3 +13,17 @@ pub fn next(max int) int {
} }
fn C.rand() int fn C.rand() int
/**
* rand_r - reentrant pseudo-random number generator
*
* @param seed byref reentrant seed, holding current state
*
* @return a value between 0 and C.RAND_MAX (inclusive)
*/
pub fn rand_r(seed &int) int {
mut rs := seed
ns := ( *rs * 1103515245 + 12345 )
*rs = ns
return ns & 0x7fffffff
}

View File

@ -28,3 +28,31 @@ fn test_rand_reproducibility() {
assert randoms1[i] == randoms2[i] assert randoms1[i] == randoms2[i]
} }
} }
fn gen_randoms_r(seed int) []int {
mut randoms := [0].repeat(20)
for i in 0..20 {
randoms[i] = rand.rand_r(&seed)
}
return randoms
}
fn test_rand_r_reproducibility() {
mut randoms1 := gen_randoms_r(42)
mut randoms2 := gen_randoms_r(42)
assert randoms1.len == randoms2.len
mut len := randoms1.len
for i in 0..len {
assert randoms1[i] == randoms2[i]
}
randoms1 = gen_randoms_r(256)
randoms2 = gen_randoms_r(256)
assert randoms1.len == randoms2.len
len = randoms1.len
for i in 0..len {
assert randoms1[i] == randoms2[i]
}
}