简体   繁体   English

Scala - 用随机数元组创建 seq

[英]Scala - create seq with tuple of random numbers

I would like to get something like: Seq((1,2), (42, 45), (54, 52), ...).我想得到类似的结果: Seq((1,2), (42, 45), (54, 52), ...).
In other words I would like to create Seq of length n with pairs of random integers.换句话说,我想用随机整数对创建长度为n Seq

I tried to to do something like:我试图做这样的事情:
(1 to n).toSeq.map(_ -> (scala.util.random.nextInteger(),scala.util.random.nextInteger() )) However, it returns some IndexedSeq instead of Seq . (1 to n).toSeq.map(_ -> (scala.util.random.nextInteger(),scala.util.random.nextInteger() ))但是,它返回一些IndexedSeq而不是Seq
Could anyone help me, please?请问有人可以帮我吗?

As explained in the comments, it is OK that it returns IndexedSeq because this is a subtype of Seq .正如评论中所解释的,它返回IndexedSeq是可以的,因为这是Seq的子类型。 But Scala has a library method called fill that will do what you want:但是 Scala 有一个名为fill的库方法可以执行您想要的操作:

Seq.fill(n)((scala.util.Random.nextInt(), scala.util.Random.nextInt()))

However it is probably best to be explicit about the actual type you want ( Vector , List etc.):但是,最好明确说明您想要的实际类型( VectorList等):

Vector.fill(n)((scala.util.Random.nextInt(), scala.util.Random.nextInt()))

This can still be assigned to a Seq but you can choose the appropriate implementation for your application.这仍然可以分配给Seq但您可以为您的应用程序选择适当的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM