如何判断两条线是否重叠?

时间:2016-10-16 22:39:00

标签: javascript geometry boolean-logic

我的函数接受两个表示线条的对象,无论它们是否重叠都应该返回。

重叠返回true,但不重叠并不会返回false

知道为什么吗?

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

3 个答案:

答案 0 :(得分:0)

您必须检查一行的开头是否在另一行的开头和结尾之间。

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

答案 1 :(得分:0)

你必须确保line2.start位于第1行,但不在最后或line1.start位于第2行,但不在它的结尾。

mov si,[bp+4]
mov di,[bp+6]
mov al,[si]
mov ah,[di]
mov [si],ah
mov [di],al

答案 2 :(得分:0)

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

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

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

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

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

您可以将<=调整为<,具体取决于您希望如何处理边缘。

&#13;
&#13;
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
&#13;
&#13;
&#13;