random_choice 0.2.0

Chooses samples randomly by their weights/probabilities.
Documentation

Rust Random Choice

Chooses samples randomly by their weights/probabilities.

Advantages

  • There is a good diversity for the case that all weights are equally distributed (in contrast to the roulette wheel selection algorithm which tends to select the same sample n times)
  • Blazingly fast: O(n) (Roulette wheel selection algorithm: O(n * log n))
  • Memory Usage: O(n); in place variant: O(1)
  • The sum of the weights don't have to be 1.0, but must not overflow

This algorithm is based on the stochastic universal sampling algorithm.

Applications

  • Evolutionary algorithms: Choose the n fittest populations by their fitness fi
  • Monte Carlo Localization: Resampling of n particles by their weight w

Usage

Add this to your Cargo.toml:

[dependencies]
random_choice = "*"

Examples

In Place Variant

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];

    random_choice().random_choice_in_place_f64(&mut samples, &weights);
 
    for sample in samples {
        print!("{}, ", sample);
    }
}

N Selection Variant

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 random_choice;
extern crate rand;

use self::random_choice::RandomChoice;
use self::rand::thread_rng;

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 mut random_choice = RandomChoice::new(thread_rng());
    random_choice.random_choice_in_place_f64(&mut samples, &weights);

    for sample in samples {
        print!("{}, ", sample);
    }
}