Detection if collision of two ranges of numbers

This is hopefully a very simple math question. If I have two ranges of numbers, then what is the easiest and most effective way to check if they collided, for example:

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 should 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
source share
5 answers

Ok, first make sure you have well-ordered pairs (maybe a good idea, 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 can simplify:

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

Edit : Oops, got this test back! Try:

$clash = !(($a2 <= $b1) || ($a1 >= $b2));
+11
source

I think it should be so simple:

clash = A_LOW <= B_HIGH AND A_HIGH >= B_LOW
+7

:
10 - 20
4 - 11//
1 - 5//
40 - 50
2 ,
x_array = array (10,4,11,40);
y_array = (20,11,5,50);

asort ($ x_array);// x
$ max_val = -1;
$ last_index = 0;
foreach ($ x_array as $each_index = > $each_x) {
   // y
  $this_y = $y_array [$ each_index];
  echo "$ this_y < $max_val";
  if ($ each_x > $max_val && $this_y > $max_val) {
    $max_val = $this_y;
   }
  {
    $last_x = $x_array [$ last_index];
    $last_y = $y_array [$ last_index];
    echo ": : ($ each_x, $this_y) ($ last_x, $last_y)";
   }
  $last_index = $each_index;
}

+3
source

Ranges are NOT compressed if and only if $ a2 <= $ b1 or $ a1> = $ b2 (provided that the ranges are specified as ordered pairs). Now cancel the condition.

+2
source

What you are looking for is intersection of arrays. http://us3.php.net/array_intersect

Basically,

$intersect = array_intersect($arr1, $arr2);
$clash = (count($intersect) > 0);

If any elements are in both $ arr1 and $ arr2, then $ intersect will display these values. Calling count () returns 1 (or more), so do> 0 gives you if $ arr1 and $ arr2 have similar elements.

0
source

All Articles