How do I generate a vector of 100 64-bit integer values in the range from 1 to 20, allowing duplicates?
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 = (0..100).map(|v| v + 1000).collect();
// [1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, ...
Splitting this up:
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 = (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 = (0..100).map(|_| rng.sample(&range)).collect();
println!("{:?}", vals);
}
(On the Playground)