#random #array #slice #pick #choose

random-pick

Pick an element from a slice randomly by given weights

20 stable releases

1.2.14 Apr 22, 2021
1.2.13 Jul 29, 2020
1.2.10 Jun 27, 2020
1.2.8 Mar 13, 2020
1.2.3 Nov 14, 2018

#133 in Algorithms

Download history 985/week @ 2021-08-10 910/week @ 2021-08-17 1519/week @ 2021-08-24 2158/week @ 2021-08-31 3848/week @ 2021-09-07 6377/week @ 2021-09-14 11408/week @ 2021-09-21 5819/week @ 2021-09-28 1129/week @ 2021-10-05 1521/week @ 2021-10-12 1289/week @ 2021-10-19 1356/week @ 2021-10-26 1195/week @ 2021-11-02 1488/week @ 2021-11-09 1505/week @ 2021-11-16 1198/week @ 2021-11-23

5,532 downloads per month
Used in 2 crates

MIT license

10KB
137 lines

Random Pick

CI

Pick an element from a slice randomly by given weights.

Example

extern crate random_pick;

enum Prize {
    Legendary,
    Rare,
    Enchanted,
    Common,
}

let prize_list = [Prize::Legendary, Prize::Rare, Prize::Enchanted, Prize::Common]; // available prizes

let slice = &prize_list;
let weights = [1, 5, 15, 30]; // a scale of chance of picking each kind of prize

let n = 1000000;
let mut counter = [0usize; 4];

for _ in 0..n {
    let picked_item = random_pick::pick_from_slice(slice, &weights).unwrap();

    match picked_item {
        Prize::Legendary=>{
            counter[0] += 1;
           }
        Prize::Rare=>{
            counter[1] += 1;
        }
        Prize::Enchanted=>{
            counter[2] += 1;
        }
        Prize::Common=>{
            counter[3] += 1;
        }
    }
}

println!("{}", counter[0]); // Should be close to 20000
println!("{}", counter[1]); // Should be close to 100000
println!("{}", counter[2]); // Should be close to 300000
println!("{}", counter[3]); // Should be close to 600000

The length of the slice is usually an integral multiple (larger than zero) of that of weights.

If you have multiple slices, you don't need to use extra space to concat them, just use the pick_from_multiple_slices function, instead of pick_from_slice.

Besides picking a single element from a slice or slices, you can also use pick_multiple_from_slice and pick_multiple_from_multiple_slices functions. Their overhead is lower than that of non-multiple-pick functions with extra loops.

Crates.io

https://crates.io/crates/random-pick

Documentation

https://docs.rs/random-pick

License

MIT

Dependencies

~0.6–1.1MB
~24K SLoC