rust-random / rand

A Rust library for random number generation.
https://crates.io/crates/rand
Other
1.65k stars 430 forks source link

Consider adding `Rng::choose` #1166

Open makoConstruct opened 3 years ago

makoConstruct commented 3 years ago

It seems that the current way to sample from a slice is s[rng.gen_range(0..s.len())]. This is not as nice as rng.sample(s) would be, but for some reason Distribution is not implemented for &[T]?

makoConstruct commented 3 years ago

I have found out about SliceRandom, but this functionality really should be discoverable in the same box as the rest of the Distribution sampling stuff rather than being hidden away in a separate trait.

vks commented 3 years ago

Distribution is already implemented for slices. Note that it is not implemented for &[T], because it requires preprocessing.

SliceRandom has to be its own trait, because "choosing without replacement" is not giving independent samples, and is therefore not supported by Distribution.

However, we could add choose as a convenience methods to Rng.

dhardy commented 2 months ago

We could add Rng::choose (supporting only slices), but it's duplicate functionality as is seen by a simple search. It also couldn't support both iterators (which need to take self by value) and slices (for which the desired receiver is normally &self).

We could implement Distribution<T> for [T], but not a mutable variant. Also, Distribution objects are usually used where it is desired to pay the set-up cost for more efficient sampling later.

Hence, I'd prefer to solve this with only documentation; the Getting Started guide should likely mention this.