Skip to main content

sample_weighted

Function sample_weighted 

Source
pub fn sample_weighted<R, F, X>(
    rng: &mut R,
    length: usize,
    weight: F,
    amount: usize,
) -> Result<IndexVec, WeightError>
where R: Rng + ?Sized, F: Fn(usize) -> X, X: Into<f64>,
Expand description

Randomly sample amount distinct indices from 0..length

The result may contain less than amount indices if insufficient non-zero weights are available. Results are returned in an arbitrary order (there is no guarantee of shuffling or ordering).

Function weight is called once for each index to provide weights.

This method is used internally by the slice sampling methods, but it can sometimes be useful to have the indices themselves so this is provided as an alternative.

Error cases:

  • WeightError::InvalidWeight when a weight is not-a-number or negative, or when infinite weights fill the reservoir before all elements have been processed (this always happens with more than amount infinite weights, and may also happen with exactly amount, depending on order).

This implementation uses O(length + amount) space and O(length) time.