scala 如何生成随机数列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9094820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate a list of random numbers?
提问by Malvolio
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:
这可能是有史以来最不重要的 Scala 问题,但它困扰着我。我将如何生成一个包含 n 个随机数的列表。到目前为止我所拥有的:
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.
哪个有效,但对我来说看起来不是很标量。我愿意接受建议。
EDIT
编辑
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
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..."
但是返回列表中每个条目的索引也是最后一个的上限。第一个数字必须小于 1,第二个数字必须小于 2,依此类推。我运行了三四次,注意到“嗯,结果总是从 0 开始……”
回答by Nicolas
You can either use Don's solutionor:
您可以使用Don 的解决方案或:
Seq.fill(n)(Random.nextInt)
Note that you don't need to create a new Randomobject, you can use the default companion object Random, as stated above.
请注意,您不需要创建新Random对象,您可以使用默认的伴生对象 Random,如上所述。
回答by Don Mackenzie
How about:
怎么样:
import util.Random.nextInt
Stream.continually(nextInt(100)).take(10)
回答by Luigi Plinge
regarding your EDIT,
关于您的编辑,
nextIntcan take an Intargument as an upper bound for the random number, so 1 to 20 map r.nextIntis the same as 1 to 20 map (i => r.nextInt(i)), rather than a more useful compilation error.
nextInt可以将Int参数作为随机数的上限,因此1 to 20 map r.nextInt与 相同1 to 20 map (i => r.nextInt(i)),而不是更有用的编译错误。
1 to 20 map (_ => r.nextInt(100))does what you intended. But it's better to use Seq.fillsince that more accurately represents what you're doing.
1 to 20 map (_ => r.nextInt(100))做你想要的。但最好使用它,Seq.fill因为它更准确地代表了你在做什么。

