porton
porton

Reputation: 5803

How to choose several random numbers from an interval?

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?

Upvotes: 1

Views: 1696

Answers (1)

Netwave
Netwave

Reputation: 42688

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

Upvotes: 4

Related Questions