tomek.xyz
tomek.xyz

Reputation: 139

Scala - create seq with tuple of random numbers

I would like to get something like: Seq((1,2), (42, 45), (54, 52), ...).
In other words I would like to create Seq of length n with pairs of random integers.

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.
Could anyone help me, please?

Upvotes: 0

Views: 273

Answers (1)

Tim
Tim

Reputation: 27421

As explained in the comments, it is OK that it returns IndexedSeq because this is a subtype of Seq. But Scala has a library method called fill that will do what you want:

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.):

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.

Upvotes: 1

Related Questions