Struct std::random::WeightedIndex
struct WeightedIndex<T> { ... }
T: Numeric
Weighted discrete distribution.
Returns an index from 0..weights.len()
with probability proportional to
the weight at that index.
Sampling from this distributions has a complexity of O(log n)
where n
is the number of
weights.
This distribution allocates a vector of cumulative weights on construction, so it needs to be freed when it is no longer needed.
Example
use std::random::{thread_rng, WeightedIndex};
let values = ["Mayo", "Mustard", "Ketchup", "BBQ Sauce"];
let dist = WeightedIndex::new(&[1, 0, 1, 2]);
defer dist.free();
// Prints "BBQ Sauce" with probability 1/2, and "Ketchup" or "Mayo"
// with probability 1/4 each
println!("{}", values[dist.sample(thread_rng())]);
Run this example
Methods
impl WeightedIndex<T> { ... }
T: Numeric
-
fn new(slice: &[T]) -> WeightedIndex<T>
Creates a new weighted index distribution from a slice of weights.
Panics if the slice is empty, if any of the weights are negative, or if the total weight is zero.
-
fn from_iter<I>(iter: &mut I) -> WeightedIndex<T>
I: Iterator<I, T>Creates a new weighted index distribution from an iterator of weights.
Panics if the iterator is empty, if any of the weights are negative, or if the total weight is zero.
-
fn sample<R>(self: &WeightedIndex<T>, rng: &mut R) -> usize
R: Rng<R>Samples a distribution using a provided random number generator.
-
fn move(self: &mut WeightedIndex<T>) -> WeightedIndex<T>
-
fn free(self: &mut WeightedIndex<T>)
Frees the memory backing the object.
Mixins
impl WeightedIndex<T> { ... }
T: Numeric
-
mixin<R> Distribution<WeightedIndex<T>, usize, R>
R: Rng<R> -
fn sample_iter(self: &Self, rng: &mut R) -> DistIterator<Self, T, R>
Raturns an iterator producing an infinite stream of values sampled from the distribution.
Example
use std::random::{thread_rng, UniformInteger}; let dist = UniformInteger::new(0..=5); // Prints 10 random numbers between 0 and 5 inclusive for i in dist.sample_iter(thread_rng()).take(10) { println!("{}", i); }
Run this example