1

I have an interval 0..N in Rust and need to choose 3 distinct random integers (with each integer in the interval having equal probabilities to be chosen).

I want this to query random servers to cross-verify data.

How to do this in Rust?

porton
  • 5,214
  • 11
  • 47
  • 95
  • 1
    Does this answer your question? [How can I generate a random number within a range in Rust?](https://stackoverflow.com/questions/19671845/how-can-i-generate-a-random-number-within-a-range-in-rust) – smitop Oct 18 '21 at 00:22
  • I think a key word you're missing in your quest is "sample". There's this but I'm not sure if it can take a "rangey"/interval instance. https://docs.rs/rand/0.8.4/rand/seq/index/fn.sample.html – nelsonjchen Oct 18 '21 at 01:55
  • Try running three steps of the [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle) to get three different number from the specified range. – rossum Oct 18 '21 at 08:14
  • @Smitop My question is about generating _distinct_ numbers. So, it's not an answer. – porton Oct 18 '21 at 14:06
  • 1
    @nelsonjchen Yes, `rand::seq::index::sample` is the answer. – porton Oct 18 '21 at 14:07
  • @rossum Your solution is _very_ inefficient. – porton Oct 18 '21 at 14:08

1 Answers1

4

You could use the rand crate, adapting the uniform distribution example

fn main() {
    use rand::distributions::Uniform;
    use rand::{thread_rng, Rng};

    let mut rng = thread_rng();
    let side = Uniform::new(-10, 10);

    for _ in 0..3 {
        println!("Point: {}", rng.sample(side));
    }
}

Playground

For distinct numbers within the range use the index::sample:

fn main() {
    use rand::{thread_rng};

    let mut rng = thread_rng();
    let results = rand::seq::index::sample(&mut rng, 10, 3).into_vec();
    println!("{:?}", results);
}

Playground

Netwave
  • 40,134
  • 6
  • 50
  • 93
  • You misread. I want 3 _distinct_ numbers. Your code sometimes output identical numbers. – porton Oct 18 '21 at 14:04
  • @porton I think you should use https://docs.rs/rand/0.8.4/rand/seq/index/fn.sample.html then. Sorry if I missread. (ill update the answers if that is what you were trying to find) – Netwave Oct 18 '21 at 14:28
  • Yes, docs.rs/rand/0.8.4/rand/seq/index/fn.sample.html is what I need. – porton Oct 18 '21 at 14:46