Skip to content

Instantly share code, notes, and snippets.

@andlima
Last active August 29, 2015 14:06
Show Gist options
  • Save andlima/f4fcae91e4b2f158136b to your computer and use it in GitHub Desktop.
Save andlima/f4fcae91e4b2f158136b to your computer and use it in GitHub Desktop.
Mersenne Twister 19937 PRNG
fn initialize_generator(mt: &mut [uint], index: &mut uint, seed: uint)
{
mt[0] = seed;
*index = 0;
for i in range(1, 624) {
mt[i] = (
(
1812433253 * (mt[i-1] ^ (mt[i-1] >> 30))
) + i
) % (1 << 32);
}
}
fn extract_number(mt: &mut [uint], index: &mut uint) -> uint
{
if *index == 0 {
generate_numbers(mt);
}
let mut y = mt[*index];
y = y ^ (y >> 11);
y = y ^ ((y << 7) & 2636928640);
y = y ^ ((y << 15) & 4022730752);
y = y ^ (y >> 18);
*index = (*index + 1) % 624;
y
}
fn generate_numbers(mt: &mut [uint])
{
for i in range(0u, 623u) {
let y = (mt[i] & 0x80000000) + (mt[(i+1) % 624] & 0x7fffffff);
mt[i] = mt[(i+397) % 624] ^ (y >> 1);
if y % 2 != 0 {
mt[i] ^= 2567483615
}
}
}
fn main() {
let mut mt = [0u, .. 624];
let mut index = 0u;
let my_seed = 10u;
initialize_generator(&mut mt, &mut index, my_seed);
for i in range(0u, 10u) {
let n = extract_number(&mut mt, &mut index);
println!("@ {} {}", i, n);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment