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<u64> = (0..100).map(|v| v + 1000).collect();
// [1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, ...
Splitting this up:
0..100
creates an iterator for 0 through 99.map
processes each item in the iterator when the iterator is processed..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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With