Skip to content

Add choose_multiple_fill for SliceRandom #982

@mendess

Description

@mendess

Background

Currently IteratorRandom provides an allocation free way to sample members from it with choose_multiple_fill, problem is it's O(n) over the size of the iterator. This makes sense but then the docs point to SliceRandom::choose_multiple which is O(amount) but it always allocates a new vec of indexes to back the iterator it returns.

I need to sample exactly 2 members of a slice in a loop, it would be nice to have a way to avoid allocating in a loop that doesn't need to as this will be a major performance hit.

Right now I have to do

let (u, w) = slice
    .choose(&mut rng)
    .and_then(|u| loop {
        let w = slice.choose(&mut rng)?;
        if w != u {
            break Some((u, w));
        }
    })?;

which I doubt is a good way to achieve randomness.

Feature request

Add to SliceRandom

fn choose_multiple_fill(
    &self,
    rng: &mut Rng,
    slice: &mut [Self::Item]
) -> usize

I can try to write a PR for this if it seems feasible but I don't have experience with rng, I would look at the rest of the implementations, specially SliceRandom::choose_multiple for inspiration.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions