Sequences

Rand implements a few common random operations on sequences via the IteratorRandom and SliceRandom traits.

Generating indices

To sample:

Shuffling

To shuffle a slice:

Sampling

The following provide a convenient way of sampling a value from a slice or iterator:

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 and O(log N) sampling
  • WeightedAliasIndex has slow setup and O(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: