Given two inclusive integer ranges [x1:x2] and [y1:y2], where x1 ≤ x2 and y1 ≤ y2, what is the most efficient way to test whether there is any overlap of the two ranges?
A simple implementation is as follows:
bool testOverlap(int x1, int x2, int y1, int y2) {
return (x1 >= y1 && x1 <= y2) ||
(x2 >= y1 && x2 <= y2) ||
(y1 >= x1 && y1 <= x2) ||
(y2 >= x1 && y2 <= x2);
}
But I expect there are more efficient ways to compute this.
What method would be the most efficient in terms of fewest operations.
You have the most efficient representation already - it's the bare minimum that needs to be checked unless you know for sure that x1 < x2 etc, then use the solutions others have provided.
You should probably note that some compilers will actually optimise this for you - by returning as soon as any of those 4 expressions return true. If one returns true, so will the end result - so the other checks can just be skipped.
If you were dealing with, given two ranges
[x1:x2]
and[y1:y2]
, natural / anti-natural order ranges at the same time where:x1 <= x2 && y1 <= y2
orx1 >= x2 && y1 >= y2
then you may want to use this to check:
they are overlapped <=>
(y2 - x1) * (x2 - y1) >= 0
where only four operations are involved:
If someone is looking for a one-liner which calculates the actual overlap:
If you want a couple fewer operations, but a couple more variables:
Here's my version:
Unless you're running some high-performance range-checker on billions of widely-spaced integers, our versions should perform similarly. My point is, this is micro-optimization.
What does it mean for the ranges to overlap? It means there exists some number C which is in both ranges, i.e.
and
Now, if we are allowed to assume that the ranges are well-formed (so that x1 <= x2 and y1 <= y2) then it is sufficient to test