Implement nested loop with condition in Scala

What is the idiomatic way to implement the following code in Scala?

for (int i = 1; i < 10; i+=2) { // i = 1, 3, 5, 7, 9 bool intercept = false; for (int j = 1; j < 10; j+=3) { // j = 1, 4, 7 if (i==j) intercept = true } if (!intercept) { System.out.println("no intercept") } } 
+4
source share
2 answers

You can use Range and friends:

 if (((1 until 10 by 2) intersect (1 until 10 by 3)).isEmpty) System.out.println("no intercept") 

This is not related to the nested loop (which you refer to in the header), but a much more idiomatic way to get the same result in Scala.

Edit: as Rex Kerr points out, the version above does not display a message each time, but the following:

 (1 until 10 by 2) filterNot (1 until 10 by 3 contains _) foreach ( _ => println("no intercept") ) 
+6
source

Edit: yelling, you type for every i . In this case:

 for (i <- 1 until 10 by 2) { if (!(1 until 10 by 3).exists(_ == i)) println("no intercept") } 

In this case, you really do not need the condition: the contains method checks what you want to check in the inner loop.

 for (i <- 1 until 10 by 2) { if (!(1 until 10 by 3).contains(i)) println("no intercept") } 
+6
source

Source: https://habr.com/ru/post/1443278/


All Articles