简体   繁体   English

在Scala中使用条件实现嵌套循环

[英]Implement nested loop with condition in Scala

What is an idiomatic way to implement the following code in Scala? 在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")
  }
}

You can use Range and friends: 你可以使用Range和朋友:

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

This doesn't involve a nested loop (which you refer to in the title), but it is a much more idiomatic way to get the same result in Scala. 这不涉及嵌套循环(您在标题中引用),但它是在Scala中获得相同结果的更惯用的方法。

Edit: As Rex Kerr points out, the version above doesn't print the message each time, but the following does: 编辑:正如Rex Kerr指出的那样,上面的版本不会每次都打印消息,但以下情况如下:

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

Edit: whoops, you print for each i . 编辑:哎呀,你打印每个i In that case: 在这种情况下:

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

In this case you don't actually need the condition, though: the contains method will check what you want checked in the inner loop. 在这种情况下,您实际上并不需要条件: contains方法将检查您要在内循环中检查的内容。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM