dsaeyrq451928 2009-09-08 22:04
浏览 85
已采纳

检测两个数字范围是否发生冲突

This is hopefully a very simple maths question. If I have two number ranges, what is the simplest and most efficient way to check if they clash, eg:

10-20 and 11-14 // clash as B is contained in A
11-15 and 20-22 // don't clash
24-26 and 20-30 // clash as A is contained in B
15-25 and 20-30 // clash as they overlap at each end

I currently have this mess, but there must be a much simpler way to do this check:

$clash = ($b1 >= $a1 && $b1 <= $a2)
    || ($b2 >= $a1 && $b2 <= $a2)
    || ($a1 >= $b1 && $a1 <= $b2)
    || ($a2 >= $b1 && $a2 <= $b2);
  • 写回答

5条回答 默认 最新

  • dsiftnc99059 2009-09-08 22:10
    关注

    Well, first make sure you have well-ordered pairs (probably a good idea anyway, depending on what you plan to do with them):

    if($a1 > $a2) {
        // swap $a1 and $a2
        $temp = $a1;
        $a1 = $a2;
        $a2 = $temp;
    }
    if($b1 > $b2) {
        // swap $b1 and $b2
        $temp = $b1;
        $b1 = $b2;
        $b2 = $temp;
    }
    

    Then you should be able to simplify to:

    $clash = ($a2 <= $b1) || ($a1 >= $b2);
    

    Edit: Whoops, got that test backwards! Try:

    $clash = !(($a2 <= $b1) || ($a1 >= $b2));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看