如何生成一定范围内的随机数向量? [英] How do I generate a vector of random numbers in a range?

查看:433
本文介绍了如何生成一定范围内的随机数向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何生成一个100个64位整数值的矢量,范围从1到20,允许重复?

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

推荐答案

这里需要一些主要内容.首先,如何创建一个包含100个计算项的向量?最简单的方法是创建100范围并映射这些项目.例如,您可以这样做:

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, ...

分解:

  1. 0..100 为0到0创建一个迭代器99
  2. .map 处理每个处理迭代器时,迭代器中的项目.
  3. .collect() 需要一个迭代器并将其转换为实现 FromIterator 的任何类型您的情况是Vec.
  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.

对此进行扩展以获取随机值,您可以使用rand板条箱的gen_range函数调整.map函数以生成介于0到20之间的随机值,以创建给定范围内的数值.

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);
}

(在操场上)

您还应该考虑使用 rand::distributions::Uniform 类型来提前创建范围,这比多次调用gen_range效率更高,然后从中提取样本100次:

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);
}

(在操场上)

这篇关于如何生成一定范围内的随机数向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆