【问题标题】:How to check if two 'lines' overlap?如何检查两条“线”是否重叠?
【发布时间】:2019-04-09 19:30:15
【问题描述】:

我知道,这是一个愚蠢的问题,但我需要检查两个时间段(epoch)是否重叠。我只是不知道这些检查是否足够。

TLPeriod.prototype.isOverlapping = function(period) {
    if( period.toPoints().start.getEpoch() < this.toPoints().start.getEpoch()
        &&
        this.toPoints().start.getEpoch() < period.toPoints().end.getEpoch())
        return true;
    if(this.toPoints().end.getEpoch() > period.toPoints().start.getEpoch())
        return true;
    return false;
};

我知道,我应该写here,但是要花很多时间才能得到答复。

可以快速总结为:

同一轴上的两条带点的线:

|(this.start),(this.end)|

&

|(period.start),(period.end)|

如何检查它们是否重叠?

OVERLAP!
|-----------|-----------------|-------------|
this.start  period.start     this.end     period.end

NO OVERLAP!
|-----------|              |-------------|
this.start  this.end     period.start  period.end

OVERLAP!
|-----------------|--------|-------------|
period.start  this.start  this.end     period.end

【问题讨论】:

  • 按开始对句点进行排序,使得(a, b) &lt; (c, d),然后它们重叠iff c &lt; d,并且包含在iff d &lt; b,并且不重叠如果b &lt; c。

标签: javascript overlap


【解决方案1】:

一个相反的问题:它们什么时候不重叠?答案是:第一个在第二个结束后开始,或者第二个在第一个结束后开始。所以

TLPeriod.prototype.isOverlapping = function(period) {
   return !(
      period.toPoints().start.getEpoch() > this.toPoints().end.getEpoch() ||
      this.toPoints().start.getEpoch() > period.toPoints().end.getEpoch()
   );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    相关资源
    最近更新 更多