【问题标题】:Scala Range contains (anything in another Range)?Scala Range 包含(另一个 Range 中的任何内容)?
【发布时间】:2017-11-10 19:53:33
【问题描述】:

我正在尝试定义一个简单的 Scala 方法来确定两个矩形是否在任何容量上重叠。我相信这样做的方法是:

if (! (Range_of_rectangle1.contains(anything in Range_of_rectangle2) ) ) => false

这需要对 x 轴和 y 轴都进行... 但是我对 Scala 还很陌生,所以我不知道如何写像 someRange.contains( anything in another Range) 这样的东西。

我目前用于确定重叠排序的代码有效,但有一些问题,我将讨论:

首先我定义了一个矩形(在我的代码中它是一个case class 是有原因的,但这与这个任务无关)。

case class Rectangle (minx: Int, maxx: Int, miny: Int, maxy: Int)

然后我创建函数来查看两个矩形是否重叠

def rectanglesOverlap(r1: Rectangle, r2:Rectangle): Boolean = {
  r2 match {
     //In English: if r2's minx OR miny are not anywhere in the range of r1's x-axis, then there's no overlap along the x-axis
     //If the range of r1's x-axis does NOT contain anything from r2's x-axis, they don't overlap
     case x_overlap1 if (! (  (r1.minx to r1.maxx).contains(r2.minx) || (r1.minx to r1.maxx).contains(r2.maxx) ) ) => false //where r1 is larger rectangle 
     case y_overlap1 if (! (  (r1.miny to r1.maxy).contains(r2.miny) || (r1.miny to r1.maxy).contains(r2.maxy) ) ) => false
     //If the range of r2's x-axis does NOT contain anything from r1's x-axis, they don't overlap
     case x_overlap2 if (! (  (r2.minx to r2.maxx).contains(r1.minx) || (r2.minx to r2.maxx).contains(r1.maxx) ) ) => false //where r2 is larger rectangle
     case y_overlap2 if (! (  (r2.miny to r2.maxy).contains(r1.miny) || (r2.miny to r2.maxy).contains(r1.maxy) ) ) => false
     case _ => true
  }
}

所以代码尝试做的是从其中一个矩形的 x 轴和 y 轴开始,并检查另一个矩形的 minx/y 或 maxx/y 是否在那里......

看到问题了吗?

当我测试它时,我得到了“错误”:

val q1 = Rectangle(1, 18, 1, 18)  
val q2 = Rectangle(1,8,8,16) 
scala> rectanglesOverlap(q1, q2) 
res0: Boolean = false

原因很明显。它是错误的,因为 q2 y 轴是 8-16,并且 q1 miny (1) 或 q1 maxy (18) 都不在 8-16 范围内。但是,很明显它们重叠。

所以知道我在概念上知道我的代码有什么问题,我正在尝试弄清楚如何以编程方式执行以下操作:

someRange.contains( anything in another Range).

但我搜索 Google 和 Stack Overflow 的努力并没有找到合适的解决方案。帮忙?

【问题讨论】:

  • ((1 to 18) intersect (8 to 16)).nonEmpty
  • @flavian - 哦,我没想到检查 Java 问题是否有类似的东西。这真是个好主意!
  • @jwvh - 你想发表你的评论作为答案,以便我接受它作为我问题的正确答案吗?

标签: scala range


【解决方案1】:

当您想知道一个集合与另一个集合的重叠位置时,您正在寻找它们的“交集”。

someRange.intersect(anotherRange)

(1 to 18) intersect (8 to 16)

并将其转换为布尔值

((1 to 18) intersect (8 to 16)).nonEmpty

【讨论】:

  • 注意这一点:intersect 是在SeqLike 中实现的,这意味着它使用迭代第一个Seq 并检查每个项目是否包含在第二个@987654327 中的幼稚方法@。对于大范围,这是非常低效的。最好查看someRange.contains(anotherRange.start) || someRange.contains(anotherRange.end)
猜你喜欢
  • 2010-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 2011-02-02
相关资源
最近更新 更多