-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoupon_collectorRS.rs
37 lines (28 loc) · 978 Bytes
/
coupon_collectorRS.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use std::collections::HashSet;
use rand::distributions::{Distribution, Uniform};
fn coupon_colector_rs(n: i32, sims: usize) -> f32 {
let mut needed_coupons = vec![0; sims];
let mut rng = rand::thread_rng();
let coupon_set = Uniform::from(1..n+1);
for trial in 0..sims {
let mut collected_coupons = HashSet::new();
let mut n_collected_coupons = 0;
let mut n_different_coupons = 0;
while n_different_coupons < n {
let coupon = coupon_set.sample(&mut rng);
n_collected_coupons += 1;
if !collected_coupons.contains(&coupon) {
collected_coupons.insert(coupon);
n_different_coupons += 1;
}
}
needed_coupons[trial] = n_collected_coupons;
}
mean(&needed_coupons)
}
fn mean(numbers: &[i32]) -> f32 {
numbers.iter().sum::<i32>() as f32 / numbers.len() as f32
}
fn main() {
println!("{}", coupon_colector_rs(30, 10))
}