Sequences
Rand implements a few common random operations on sequences via the
IteratorRandom
and SliceRandom
traits.
Generating indices
To sample:
- a single index within a given range, use
Rng::gen_range
- multiple distinct indices from
0..length
, useindex::sample
- multiple distinct indices from
0..length
with weights, useindex::sample_weighted
Shuffling
To shuffle a slice:
SliceRandom::shuffle
: fully shuffle a sliceSliceRandom::partial_shuffle
: partial shuffle; useful to extractamount
random elements in random order
Sampling
The following provide a convenient way of sampling a value from a slice or iterator:
SliceRandom::choose
: sample one element from a slice (by ref)SliceRandom::choose_mut
: sample one element from a slice (by ref mut)SliceRandom::choose_multiple
: sample multiple distinct elements from a slice (returns iterator of references to elements)IteratorRandom::choose
: sample one element from an iterator (by value)IteratorRandom::choose_stable
: sample one element from an iterator (by value), where RNG calls are unaffected by the iterator'ssize_hint
IteratorRandom::choose_multiple_fill
: sample multiple elements, placing into a bufferIteratorRandom::choose_multiple
: sample multiple elements, returning aVec
Note that operating on an iterator is often less efficient than operating on a slice.
Weighted sampling
For example, weighted sampling could be used to model the colour of a marble sampled from a bucket containing 5 green, 15 red and 80 blue marbles.
With replacement
Sampling with replacement implies that any sampled values (marbles) are replaced (thus, the probability of sampling each variant is not affected by the action of sampling).
This is implemented by the following distributions:
WeightedIndex
has fast setup andO(log N)
samplingWeightedAliasIndex
has slow setup andO(1)
sampling, thus may be faster with a large number of samples
For convenience, you may use:
Without replacement
Sampling without replacement implies that the action of sampling modifies the
distribution. Since the Distribution
trait is built around the idea of
immutable distributions, we offer the following:
SliceRandom::choose_multiple_weighted
: sampleamount
distinct values from a slice with weightsindex::sample_weighted
: sampleamount
distinct indices from a range with weights- Implement yourself: see the section in Random processes