0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

added the Breaks implicits in order to make the code work.
Still not right. For example, I can tell you that the value of i and j by the end of the execution will be 0 and arrB.length - 1.
Not the point of the what the OP is asking. He wants to know how to have two different counters in one loop. That's it. Also just added possible values to show how to I will get i to be arrB.lenght -1 and j to be 0 at the end of the execution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.