Advertisement
hoewarden

Untitled

Sep 28th, 2019
424
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.68 KB | None | 0 0
  1. // implementing mystical rand5() using existing library
  2. fn rand5() -> u64 {
  3.     rand::random::<u64>() % 5
  4. }
  5.  
  6. // on each step val is a random number in range (0..max-1), this is how entropy is stored
  7. struct Generator {
  8.     val : u64,
  9.     max : u64,
  10.     // just statistics...
  11.     entropy_input : f64,
  12.     entropy_output : f64,
  13. }
  14.  
  15. impl Generator {
  16.     fn new() -> Generator {
  17.         Generator{
  18.             val : 0,
  19.             max : 1,
  20.             entropy_input : 0.0,
  21.             entropy_output : 0.0,
  22.         }
  23.     }
  24.     fn rand(&mut self, n : u32) -> u32 {
  25.         loop {
  26.             let quotient = self.max / (n as u64);
  27.             let good_max = quotient * (n as u64);
  28.             if good_max > self.val {
  29.                 let res = (self.val % (n as u64)) as u32;
  30.                 self.val /= n as u64;
  31.                 self.max = quotient;
  32.                 self.entropy_output += (n as f64).log(2.0);
  33.                 return res;
  34.             } else {
  35.                 // next line is "val += max * rand5()" but with int64 overflow check
  36.                 self.val = self.max.checked_mul(rand5()).expect("Generator overheated!")
  37.                     .checked_add(self.val).expect("Generator overheated!");
  38.                 // next line is "max *= 5" but with int64 overflow check
  39.                 self.max *= self.max.checked_mul(5).expect("Generator overheated!");
  40.                 self.entropy_input += 5f64.log(2.0);
  41.             }
  42.         }
  43.     }
  44. }
  45.  
  46. fn main() {
  47.     let mut gen = Generator::new();
  48.     for _i in 0..5000 {
  49.         print!("{}", gen.rand(7));
  50.     }
  51.     println!("");
  52.     println!("Entory consumed: {}", gen.entropy_input);
  53.     println!("Entory produced: {}", gen.entropy_output);
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement