我正在尝试定义一个简单的Scala方法来确定两个矩形是否在任何容量中重叠。我相信这样做的方式将是:
if (! (Range_of_rectangle1.contains(anything in Range_of_rectangle2) ) ) => false
这需要针对x轴和y轴进行...
但我对Scala足够新,我不确定如何编写类似someRange.contains( anything in another Range)
的内容。
我目前用于确定重叠分类的代码有效但有一些问题,我将讨论:
首先我定义一个Rectangle(并且我的代码中有一个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 OR 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的努力还没有得到正确的解决方案。帮助
答案 0 :(得分:1)
当你想知道一个集合与另一个集合重叠的地方时,你正在寻找他们的“交集”。
someRange.intersect(anotherRange)
或
(1 to 18) intersect (8 to 16)
并将其变为布尔
((1 to 18) intersect (8 to 16)).nonEmpty