我怎么知道两条线是否重叠?

How can I find out if two lines overlap?

本文关键字:重叠 是否 两条线 我怎么知道      更新时间:2023-09-26

我的函数接受两个表示直线的对象,并且应该返回它们是否重叠。

重叠返回true,但不重叠似乎不返回false

知道为什么吗?

function checkOverlap (line1, line2) {
  if (line2.start <= line1.end || line1.start <= line2.end) {
    return true;
  } else {
    return false;
  }
}

你必须检查一行的开始是否在另一行的开始和结束之间。

  if((line2.start <= line1.end && line2.start >=line1.start) || (line1.start <=line2.end && line1.start >= line2.start)) { 
       return true;
    }

我认为这是最简单的逻辑。

A.start <= B.end && B.start <= A.end

很容易理解为什么这是有意义的,如果你考虑某个点,X,存在于两个范围内(假设重叠)…

A    (start)-------- X --------(end)
B        (start)---- X -------------(end)

想象一下,在要求它们不能越过X的情况下推动起点和终点(如果可以,那么X将不再在两个范围内)。很容易看出A开始总是在B结束之前,反之亦然。

你可以调整<=<取决于你想如何处理边缘。

console.clear()
let l = console.log
function checkOverlap(A, B){
  return (A.start <= B.end && B.start <= A.end)
}
// Checking All combinations
l(checkOverlap({start: 0, end: 2},{start: 3, end: 5})) // false
l(checkOverlap({start: 0, end: 4},{start: 3, end: 5})) // true
l(checkOverlap({start: 0, end: 6},{start: 3, end: 5})) // true
l(checkOverlap({start: 3, end: 5},{start: 0, end: 2})) // false
l(checkOverlap({start: 3, end: 5},{start: 0, end: 4})) // true
l(checkOverlap({start: 3, end: 5},{start: 0, end: 6})) // true

你必须确保line2。Start位于line1,但不位于end或line1。

if ( (line2.start >= line1.start and line2.start < line1.end)
     OR (line1.start >= line2.start and line1.start < line2.end) ) {
    // We have an overlap
}