Skip to content

Single item version of sample_iter ? #432

@dtrebilco

Description

@dtrebilco

Would it be worth adding a single item version of seq sample_iter()? My use cases typically only need one item. Code like this:

pub fn sample_one_iter<T, I, R>(rng: &mut R, iterable: I) -> Option<T>
    where I: IntoIterator<Item=T>,
          R: Rng + ?Sized,
{
    let mut count : usize = 0;
    let mut ret_val = None;
    for i in iterable {
        count += 1;
        if Uniform::sample_single(0, count, rng) == 0 {
            ret_val = Some(i);
        }
    }
    ret_val
}

As the current version does allocate memory which is a waste in the single case. For completeness you could also add the slice versions, but it does border on trivial.

pub fn sample_one_slice<R, T>(rng: &mut R, slice: &[T]) -> T
    where R: Rng + ?Sized,
          T: Clone
{
    slice[Uniform::sample_single(0, slice.len(), rng)].clone()
}

pub fn sample_one_slice_ref<'a, R, T>(rng: &mut R, slice: &'a [T]) -> &'a T
    where R: Rng + ?Sized
{

    &slice[Uniform::sample_single(0, slice.len(), rng)]
}

I can do a PR if needed.

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