|
| 1 | +extern crate rand; |
| 2 | +use rand::seq::SliceRandom; |
| 3 | +use rand::Rng; |
| 4 | + |
| 5 | + |
| 6 | +pub fn add_globals() -> Res { |
| 7 | + let mut globals = HashMap::new(); |
| 8 | + globals.insert(String::from("new"), Object::Inbuilt(new)); |
| 9 | + globals.insert(String::from("random"), Object::Inbuilt(random)); |
| 10 | + globals.insert(String::from("uniform"), Object::Inbuilt(uniform)); |
| 11 | + globals.insert(String::from("randint"), Object::Inbuilt(randint)); |
| 12 | + globals.insert(String::from("choice"), Object::Inbuilt(choice)); |
| 13 | + globals.insert(String::from("shuffle"), Object::Inbuilt(shuffle)); |
| 14 | + |
| 15 | + |
| 16 | + Res { |
| 17 | + globals, |
| 18 | + raw: None, |
| 19 | + } |
| 20 | +} |
| 21 | +pub struct SimpleRandom { |
| 22 | + rng: rand::rngs::ThreadRng, |
| 23 | +} |
| 24 | + |
| 25 | +impl SimpleRandom { |
| 26 | + pub fn new() -> Self { |
| 27 | + SimpleRandom { rng: rand::thread_rng() } |
| 28 | + } |
| 29 | + |
| 30 | + pub fn random(&mut self) -> f64 { |
| 31 | + self.rng.gen::<f64>() |
| 32 | + } |
| 33 | + |
| 34 | + pub fn uniform(&mut self, a: f64, b: f64) -> f64 { |
| 35 | + self.rng.gen_range(a..b) |
| 36 | + } |
| 37 | + |
| 38 | + pub fn randint(&mut self, a: i64, b: i64) -> i64 { |
| 39 | + self.rng.gen_range(a..=b) |
| 40 | + } |
| 41 | + |
| 42 | + pub fn choice<T: Clone>(&mut self, seq: &[T]) -> T { |
| 43 | + seq.choose(&mut self.rng).unwrap().clone() |
| 44 | + } |
| 45 | + |
| 46 | + pub fn shuffle<T>(&mut self, x: &mut Vec<T>) { |
| 47 | + x.shuffle(&mut self.rng); |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | + |
0 commit comments