如何生成随机数列表? [英] How to generate a list of random numbers?

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

问题描述

这可能是有史以来最不重要的 Scala 问题,但它困扰着我.我将如何生成一个包含 n 个随机数的列表.到目前为止我所拥有的:

This might be the least important Scala question ever, but it's bothering me. How would I generate a list of n random number. What I have so far:

def n_rands(n : Int) = {
 val r = new scala.util.Random
 1 to n map { _ => r.nextInt(100) } 
}

哪个有效,但对我来说看起来不是很标量.我愿意接受建议.

Which works, but doesn't look very Scalarific to me. I'm open to suggestions.

编辑

不是因为它很相关,而是因为它很有趣而且回想起来很明显,以下看起来是有效的:

Not because it's relevant so much as it's amusing and obvious in retrospect, the following looks like it works:

1 to 20 map r.nextInt

但是返回列表中每个条目的索引也是最后一个的上限.第一个数字必须小于 1,第二个数字必须小于 2,依此类推.我跑了三四次,发现嗯,结果总是从 0 开始……"

But the index of each entry in the returned list is also the upper bound of that last. The first number must be less than 1, the second less than 2, and so on. I ran it three or four times and noticed "Hmmm, the result always starts with 0..."

推荐答案

您可以使用 Don 的解决方案 或:

Seq.fill(n)(Random.nextInt)

请注意,您不需要创建新的 Random 对象,您可以使用默认的伴生对象 Random,如上所述.

Note that you don't need to create a new Random object, you can use the default companion object Random, as stated above.

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

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