# Function rand::seq::index::sample_weighted

source · ```
pub fn sample_weighted<R, F, X>(
rng: &mut R,
length: usize,
weight: F,
amount: usize
) -> Result<IndexVec, WeightError>
```

Available on

**crate features**only.`alloc`

and `std`

## Expand description

Randomly sample exactly `amount`

distinct indices from `0..length`

, and
return them in an arbitrary order (there is no guarantee of shuffling or
ordering). The weights are to be provided by the input function `weights`

,
which will be called once for each index.

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.`WeightError::InsufficientNonZero`

when fewer than`amount`

weights are positive.

This implementation uses `O(length + amount)`

space and `O(length)`

time.