Dust009
Dust009

Reputation: 335

Scala: Generate tuple of Ints

I want to generate a Vector of tuple of two Ints. For now, I do as follows:

(0 until 100).map(x => (x+1 until 100).map(y => (x,y))).flatten.filter { ... }

I wondered if there were any more efficient way to do this. I have the feeling that "flatten" slows down the code. Do I have to use "flatten" or can I use something else ?

PS1: If I don't use "flatten", I have: Vector(Vector(a,b),Vector(c,d),...) and not Vector((a,b),(c,d),...).

PS2: I use (x+1 until 100) in the second generator as I'm not interested in having tuples (a,b) and (b,a).

Upvotes: 0

Views: 216

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170919

map(f).flatten can be shortened to flatMap(f), so you'll get

(0 until 100).flatMap(x => (x+1 until 100).map(y => (x,y))).filter(...)

This is equivalent to Tzach Zohar's answer, but you can see the relation. It may also be worthwhile to move filter inside flatMap (it will get called more times, but you'll get smaller intermediate collections).

Upvotes: 0

Tzach Zohar
Tzach Zohar

Reputation: 37852

for {
  i <- 0 until 100
  j <- i+1 until 100
} yield (i,j)

Upvotes: 7

Related Questions