user2975535 user2975535 - 2 months ago 15
Scala Question

Scala increment multiple variable in for loop

I'm looking for a way to increment two variables in for loop like it can be done in Java:

for (int j = column + 1, i = row + 1; j < size && i < size; j++, i++)


In Scala if I write

for(j <- start to end; i <- start2 to end2)


this converts to nested loop but I need it to run in a raw and stop when first increment go to end.

Answer

You can write it like this:

val column = 5; val row = 3; val size = 10; // some input..

for {
  (i, j) <- (row + 1 to size - 1) zip (column + 1 to size - 1)
} {
  println(s"i=$i j=$j")
}

/* prints:
i=4 j=6
i=5 j=7
i=6 j=8
i=7 j=9
*/

The trick is, you do not want to have all combinations (for { i <- ... ; j <- ... }) of i's and j's. Rather you want them to increment together.

So you can create one range (start to end) and zip it with the other one. (The operation will drop the tail of longer sequence -- that basically ensures the j < size && i < size condition.)

And the rest is just a syntax sugar for matching the zipped tuples as i and j variables.

Comments