本文介绍了测试一个范围是否与另一个数字范围相交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个数字范围:

  • $startTime$endTime
  • $offerStartTime$offerEndTime

上述每个变量都是整数.

我想看看 offerStartTimeofferEndTime 的范围是否在 startTimeendTime 范围内.

例如,如果 startTimeendTime 范围是:10 到 20,那么以下示例范围将返回 true:>

  • offerStartTime: 5, offerEndTime: 11
  • offerStartTime: 5, offerEndTime: 100
  • offerStartTime: 10, offerEndTime: 15
  • offerStartTime:10,offerEndTime:100
  • offerStartTime: 12, offerEndTime: 15
  • offerStartTime:19,offerEndTime:100

以下将返回false:

  • offerStartTime: 1, offerEndTime: 3
  • offerStartTime:90,offerEndTime:100
  • offerStartTime: 1, offerEndTime: 10
  • offerStartTime:20,offerEndTime:100

我该怎么做?理想情况下需要 PHP 中的答案,但伪代码也可以.

解决方案

如果您只是检查报价的任何部分是否与范围的任何部分重叠,这很简单.

if ($offerStartTime < $endTime && $offerEndTime > $startTime) {echo '范围重叠';}

这是一张代表重叠和非重叠的所有可能性的图片,以直观地说明为什么会这样.

根据您的输入和预期的错误输出,我使用了 <>.如果您还想包括在某个点相交的范围,则需要使用 <=>= 代替.

I have 2 range of numbers:

  • $startTime to $endTime
  • $offerStartTime to $offerEndTime

Each of the above variables are integers.

I want to see if the range offerStartTime to offerEndTime falls in the range startTime and endTime.

For example, if the startTime and endTime range was: 10 to 20, then the following example ranges would return true:

  • offerStartTime: 5, offerEndTime: 11
  • offerStartTime: 5, offerEndTime: 100
  • offerStartTime: 10, offerEndTime: 15
  • offerStartTime: 10, offerEndTime: 100
  • offerStartTime: 12, offerEndTime: 15
  • offerStartTime: 19, offerEndTime: 100

The following would return false:

  • offerStartTime: 1, offerEndTime: 3
  • offerStartTime: 90, offerEndTime: 100
  • offerStartTime: 1, offerEndTime: 10
  • offerStartTime: 20, offerEndTime: 100

How can I do this?Would ideally like answers in PHP, but pseudo code would be fine.

解决方案

If you are just checking whether any part of the offer overlaps any part of the range, it's simple.

if ($offerStartTime < $endTime && $offerEndTime > $startTime)  {
    echo 'The ranges overlap';
}

Here's a picture representing all the possibilities of overlap and non-overlap to visualize why this works.

Based on your inputs and expected false outputs, I used < and >. If you wanted to also include ranges that intersected at a point, you would need to use <= and >= instead.

这篇关于测试一个范围是否与另一个数字范围相交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-15 07:08