Swult

Coin Flipper

Nov 8th, 2025 (edited)
646
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.92 KB | None | 0 0
  1. /*
  2. My found times:
  3. Debug (cargo run):               1.774342667s
  4. Release (cargo run --release):   14.744833ms
  5. Parallel (cargo run --release):  1.598625ms
  6. */
  7.  
  8. use std::time::Instant;
  9. use rayon::prelude::*;
  10.  
  11. fn flip_coins(num_heads: u32) -> bool {
  12.     let mut heads_in_a_row = 0;
  13.  
  14.     while heads_in_a_row < num_heads {
  15.         if rand::random_bool(0.5) {
  16.             heads_in_a_row += 1;
  17.         } else {
  18.             return false;
  19.         }
  20.     }
  21.  
  22.     true
  23. }
  24.  
  25. fn main() {
  26.     let num_heads = 20;
  27.  
  28.     // Normal version
  29.     let start_time = Instant::now();
  30.     while !flip_coins(num_heads) {
  31.         continue;
  32.     }
  33.     println!("Normal version: {:?}", start_time.elapsed());
  34.  
  35.     // Parallel version
  36.     let start_time = Instant::now();
  37.     (0u64..u64::MAX)
  38.         .into_par_iter()
  39.         .find_any(|_| flip_coins(num_heads));
  40.    
  41.     println!("Parallel version: {:?}", start_time.elapsed());
  42. }
Advertisement
Add Comment
Please, Sign In to add comment