Skip to content

Instantly share code, notes, and snippets.

@yodalee
Created June 23, 2020 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yodalee/62b706eccf71548ba04c8a82331e44a7 to your computer and use it in GitHub Desktop.
Save yodalee/62b706eccf71548ba04c8a82331e44a7 to your computer and use it in GitHub Desktop.
Random number generator in Rust with stated structure
use std::time::{SystemTime, UNIX_EPOCH};
const SEED_MAX:u64 = 9999997;
struct RandomGen {
seed: u64
}
impl RandomGen {
pub fn new(seed: u64) -> Self {
Self {
seed: seed
}
}
pub fn random(&mut self) -> f64 {
self.seed = (self.seed + 37) % SEED_MAX;
let x = (self.seed as f64).sin() * 93177.0;
x - x.floor()
}
}
fn main() {
let start = SystemTime::now();
let since_the_epoch = start
.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
let seed = since_the_epoch.as_secs() * 1000 + since_the_epoch.subsec_nanos() as u64 / 1_000_000;
let mut rndgen = RandomGen::new(seed);
for _ in 1..10 {
println!("{}", rndgen.random());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment