nolio
nolio

Reputation: 83

For loop with multiple non-nested counters in scala

I have this code snippet in java

int[] arrA = ...;
int[] arrB = ...;
int n = ...;
boolean isPermuting = true;
for(int i = 0, j = arrB.length - 1; i < n; i++, j--) {
   if(arrA[i] + arrB[j] < k) {
      isPermuting = false;
      break;
   }
}

I know there is a way to put multiple counters in the same for loop in scala but the end up being nested. For example:

for(i <- 1 to 10 ; j <- 10 to 20) // in scala

is the same as

for(int i = 1; i <= 10 ; i ++){
   for(int j = 10; j <= 20; j++){ // in java

but I don't know how to do this for non nested counters

Upvotes: 0

Views: 175

Answers (1)

locorecto
locorecto

Reputation: 1203

I don't know if there is a way to do with for loops in scala inline but you can use while loops and change the organization a bit. Make sure you import Breaks from utils.

 import scala.util.control.Breaks._

  var n = 4
  var k = 3
  val arrA : Array[Int] = Array(8, 2, 3, 4, 5)
  val arrB : Array[Int] = Array(5, 4, 3, 2, 6)
  var isPermuting: Boolean = true
  var i: Int = 0
  var j: Int = arrB.length - 1
  breakable {
    while (i < n) {
      if (arrA(i) + arrB(j) < k) {
        isPermuting = false
        break
      }

      i += 1
      j -= 1
    }
  }

  print(isPermuting)

EDIT: This might not be the cleanest way to do it but coming from java is easy enough to understand. I hope it helps

Upvotes: 1

Related Questions