Trait IndexedRandom
pub trait IndexedRandom: Index<usize>
Extension trait on indexable lists, providing random sampling methods.
This trait is implemented on [T] slice types. Other types supporting
[std::ops::Index<usize>] may implement this (only Self::len must be
specified).
Required Methods
fn len(&self) -> usizeThe length
Provided Methods
fn is_empty(&self) -> boolTrue when the length is zero
fn choose<R>(&self, rng: &mut R) -> Option<&Self::Output> where R: Rng + ?Sized,Uniformly sample one element
Returns a reference to one uniformly-sampled random element of the slice, or
Noneif the slice is empty.For slices, complexity is
O(1).Example
use IndexedRandom; let choices = ; let mut rng = rng; println!; assert_eq!;fn choose_iter<R>(&self, rng: &mut R) -> Option<impl Iterator<Item = &Self::Output>> where R: Rng + ?Sized,Return an iterator which samples from
selfwith replacementReturns
Noneif and only ifself.is_empty().Example
use IndexedRandom; let choices = ; let mut rng = rng; for choice in choices.choose_iter.unwrap.takefn sample<R>(&self, rng: &mut R, amount: usize) -> IndexedSamples<'_, Self, Self::Output> where Self::Output: Sized, R: Rng + ?Sized,Uniformly sample
amountdistinct elements from selfChooses
amountelements from the slice at random, without repetition, and in random order. The returned iterator is appropriate both for collection into aVecand filling an existing buffer (see example).In case this API is not sufficiently flexible, use
index::sample.For slices, complexity is the same as
index::sample.Example
use IndexedRandom; let mut rng = &mut rng; let sample = "Hello, audience!".as_bytes; // collect the results into a vector: let v: = sample.sample.cloned.collect; // store in a buffer: let mut buf = ; for in sample.sample.zipfn sample_array<R, const N: usize>(&self, rng: &mut R) -> Option<[Self::Output; N]> where Self::Output: Clone + Sized, R: Rng + ?Sized,Uniformly sample a fixed-size array of distinct elements from self
Chooses
Nelements from the slice at random, without repetition, and in random order.For slices, complexity is the same as
index::sample_array.Example
use IndexedRandom; let mut rng = &mut rng; let sample = "Hello, audience!".as_bytes; let a: = sample.sample_array.unwrap;fn choose_weighted<R, F, B, X>(&self, rng: &mut R, weight: F) -> Result<&Self::Output, WeightError> where R: Rng + ?Sized, F: Fn(&Self::Output) -> B, B: SampleBorrow<X>, X: SampleUniform + Weight + PartialOrd<X>,Biased sampling for one element
Returns a reference to one element of the slice, sampled according to the provided weights.
The specified function
weightmaps each itemxto a relative likelihoodweight(x). The probability of each item being selected is thereforeweight(x) / s, wheresis the sum of allweight(x).For slices of length
n, complexity isO(n). For more information about the underlying algorithm, see theWeightedIndexdistribution.See also
choose_weighted_mut.Example
use *; let choices = ; let mut rng = rng; // 50% chance to print 'a', 25% chance to print 'b', 25% chance to print 'c', // and 'd' will never be printed println!;fn choose_weighted_iter<R, F, B, X>(&self, rng: &mut R, weight: F) -> Result<impl Iterator<Item = &Self::Output>, WeightError> where R: Rng + ?Sized, F: Fn(&Self::Output) -> B, B: SampleBorrow<X>, X: SampleUniform + Weight + PartialOrd<X>,Biased sampling with replacement
Returns an iterator which samples elements from
selfaccording to the given weights with replacement (i.e. elements may be repeated).See also doc for
Self::choose_weighted.fn sample_weighted<R, F, X>(&self, rng: &mut R, amount: usize, weight: F) -> Result<IndexedSamples<'_, Self, Self::Output>, WeightError> where Self::Output: Sized, R: Rng + ?Sized, F: Fn(&Self::Output) -> X, X: Into<f64>,Biased sampling of
amountdistinct elementsSimilar to
sample, but where the likelihood of each element's inclusion in the output may be specified. Zero-weighted elements are never returned; the result may therefore contain fewer elements thanamounteven whenself.len() >= amount. The elements are returned in an arbitrary, unspecified order.The specified function
weightmaps each itemxto a relative likelihoodweight(x). The probability of each item being selected is thereforeweight(x) / s, wheresis the sum of allweight(x).This implementation uses
O(length + amount)space andO(length)time. Seeindex::sample_weightedfor details.Example
use *; let choices = ; let mut rng = rng; // First Draw * Second Draw = total odds // ----------------------- // (50% * 50%) + (25% * 67%) = 41.7% chance that the output is `['a', 'b']` in some order. // (50% * 50%) + (25% * 67%) = 41.7% chance that the output is `['a', 'c']` in some order. // (25% * 33%) + (25% * 33%) = 16.6% chance that the output is `['b', 'c']` in some order. println!;fn choose_multiple<R>(&self, rng: &mut R, amount: usize) -> IndexedSamples<'_, Self, Self::Output> where Self::Output: Sized, R: Rng + ?Sized,Deprecated: use
Self::sampleinsteadfn choose_multiple_array<R, const N: usize>(&self, rng: &mut R) -> Option<[Self::Output; N]> where Self::Output: Clone + Sized, R: Rng + ?Sized,Deprecated: use
Self::sample_arrayinsteadfn choose_multiple_weighted<R, F, X>(&self, rng: &mut R, amount: usize, weight: F) -> Result<IndexedSamples<'_, Self, Self::Output>, WeightError> where Self::Output: Sized, R: Rng + ?Sized, F: Fn(&Self::Output) -> X, X: Into<f64>,Deprecated: use
Self::sample_weightedinstead
Implementors
impl<T> IndexedRandom for [T]