[−][src]Trait rand::seq::IteratorRandom
Extension trait on iterators, providing random sampling methods.
This trait is implemented on all sized iterators, providing methods for
choosing one or more elements. You must use
this trait:
use rand::seq::IteratorRandom; fn main() { let mut rng = rand::thread_rng(); let faces = "😀😎😐😕😠😢"; println!("I am {}!", faces.chars().choose(&mut rng).unwrap()); }
Example output (non-deterministic):
I am 😀!
Provided methods
fn choose<R: ?Sized>(self, rng: &mut R) -> Option<Self::Item> where
R: Rng,
R: Rng,
Choose one element at random from the iterator.
Returns None
if and only if the iterator is empty.
This method uses [Iterator::size_hint
] for optimisation. With an
accurate hint and where [Iterator::nth
] is a constant-time operation
this method can offer O(1)
performance. Where no size hint is
available, complexity is O(n)
where n
is the iterator length.
Partial hints (where lower > 0
) also improve performance.
For slices, prefer [SliceRandom::choose
] which guarantees O(1)
performance.
fn choose_multiple_fill<R: ?Sized>(
self,
rng: &mut R,
buf: &mut [Self::Item]
) -> usize where
R: Rng,
self,
rng: &mut R,
buf: &mut [Self::Item]
) -> usize where
R: Rng,
Collects values at random from the iterator into a supplied buffer until that buffer is filled.
Although the elements are selected randomly, the order of elements in the buffer is neither stable nor fully random. If random ordering is desired, shuffle the result.
Returns the number of elements added to the buffer. This equals the length of the buffer unless the iterator contains insufficient elements, in which case this equals the number of elements available.
Complexity is O(n)
where n
is the length of the iterator.
For slices, prefer [SliceRandom::choose_multiple
].
fn choose_multiple<R: ?Sized>(
self,
rng: &mut R,
amount: usize
) -> Vec<Self::Item> where
R: Rng,
self,
rng: &mut R,
amount: usize
) -> Vec<Self::Item> where
R: Rng,
Collects amount
values at random from the iterator into a vector.
This is equivalent to choose_multiple_fill
except for the result type.
Although the elements are selected randomly, the order of elements in the buffer is neither stable nor fully random. If random ordering is desired, shuffle the result.
The length of the returned vector equals amount
unless the iterator
contains insufficient elements, in which case it equals the number of
elements available.
Complexity is O(n)
where n
is the length of the iterator.
For slices, prefer [SliceRandom::choose_multiple
].