[][src]Function rand::seq::sample_iter

pub fn sample_iter<T, I, R: ?Sized>(
    rng: &mut R,
    iterable: I,
    amount: usize
) -> Result<Vec<T>, Vec<T>> where
    I: IntoIterator<Item = T>,
    R: Rng

Randomly sample amount elements from a finite iterator.

The following can be returned:

  • Ok: Vec of amount non-repeating randomly sampled elements. The order is not random.
  • Err: Vec of all the elements from iterable in sequential order. This happens when the length of iterable was less than amount. This is considered an error since exactly amount elements is typically expected.

This implementation uses O(len(iterable)) time and O(amount) memory.

Example

use rand::{thread_rng, seq};

let mut rng = thread_rng();
let sample = seq::sample_iter(&mut rng, 1..100, 5).unwrap();
println!("{:?}", sample);