Home

Awesome

Rust Random Choice

Chooses samples randomly by their weights/probabilities.

Advantages

This algorithm is based on the stochastic universal sampling algorithm.

Applications

Usage

Add this to your Cargo.toml:

[dependencies]
random_choice = "*"

Examples

Default Way

extern crate random_choice;
use self::random_choice::random_choice;

fn main() {
    let mut samples = vec!["hi", "this", "is", "a", "test!"];
    let weights: Vec<f64> = vec![5.6, 7.8, 9.7, 1.1, 2.0];

    let number_choices = 100;
    let choices = random_choice().random_choice_f64(&samples, &weights, number_choices);

    for choice in choices {
        print!("{}, ", choice);
    }
}

With Custom Seed

extern crate rand;
extern crate random_choice;
use random_choice::RandomChoice;
use rand::SeedableRng;

fn main() {
    let mut samples = vec!["hi", "this", "is", "a", "test!"];
    let weights: Vec<f64> = vec![5.6, 7.8, 9.7, 1.1, 2.0];

    let rng = rand::StdRng::from_seed(&[5000, 44, 55, 199]);

    let mut random_choice = RandomChoice::new(rng);
    let number_choices = 100;
    let choices = random_choice.random_choice_f64(&mut samples, &weights, number_choices);

    for choice in choices {
        print!("{}, ", choice);
    }
}