Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a vector of random numbers in a range?

How do I generate a vector of 100 64-bit integer values in the range from 1 to 20, allowing duplicates?

like image 520
mrsteve Avatar asked Jan 12 '18 01:01

mrsteve


1 Answers

There are a few main pieces that you need here. First, how to create a vector of 100 calculated items? The easiest way is to create a range of 100 and map over those items. For instance you could do:

let vals: Vec<u64> = (0..100).map(|v| v + 1000).collect();
// [1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, ...

Splitting this up:

  1. 0..100 creates an iterator for 0 through 99
  2. .map processes each item in the iterator when the iterator is processed.
  3. .collect() takes an iterator and converts it into any type that implements FromIterator which in your case is Vec.

Expanding on this for your random values, you can adjust the .map function to generate a random value from 0 to 20 using the rand crate's gen_range function to create a numeric value within a given range.

use rand::Rng; // 0.6.5

fn main() {
    let mut rng = rand::thread_rng();

    let vals: Vec<u64> = (0..100).map(|_| rng.gen_range(0, 20)).collect();

    println!("{:?}", vals);
}

(On the Playground)

You should also consider using the rand::distributions::Uniform type to create the range up front, which is is more efficient than calling gen_range multiple times, then pull samples from it 100 times:

use rand::{distributions::Uniform, Rng}; // 0.6.5

fn main() {
    let mut rng = rand::thread_rng();
    let range = Uniform::new(0, 20);

    let vals: Vec<u64> = (0..100).map(|_| rng.sample(&range)).collect();

    println!("{:?}", vals);
}

(On the Playground)

like image 109
loganfsmyth Avatar answered Oct 11 '22 17:10

loganfsmyth