Is there an effective way to find the overlap between two ranges?
Practically, the two ranges marked as (a - c), and (b - d), and I assume (c > a) && (d > b).
(b <= a <= d) which means if ((a >= b) && (d > a)) (b <= c <= d) which means if ((c >= b) && (d >= c)) (a <= b <= c) which means if ((b > a) && (c > b)) (a <= d <= c) which means if ((d > a) && (c > d))
But it never ends, because in this way I can find only one range at the time, and in each if I have to check the other cases as well.
For exemple, if the first condition (1) correct, I know what happening with the start of the range (a) I still need to check the others for the end of the range (c).
Not to mention that all this works in the case that (c > a) && (d > b), and not one of them is equal to another.
1) Sort all intervals in increasing order of start time. This step takes O(nLogn) time. 2) In the sorted array, if start time of an interval is less than end of previous interval, then there is an overlap.
Intersect Operator in Excel can be used to find the intersecting value(s) of two lists/ranges. This an unusual operator as it is represented by a space character (yes that's right). If you use a space character in between two ranges, then it becomes the Intersect operator in Excel.
If both ranges have at least one common point, then we say that they're overlapping. In other words, we say that two ranges and are overlapping if: On the other hand, non-overlapping ranges don't have any points in common.
Two ranges overlap in one of two basic cases:
Conversely, they do not overlap only if neither endpoint of each range is contained within the other range (cases 11 and 12 in your diagram). We can check whether the low end of either range is past the high end of the other, to detect both those cases:
if (a > d || c < b) { // no overlap } else { // overlap }
We can invert the condition and then use DeMorgan's laws to swap the order, if that's preferable:
if (a <= d && c >= b) { // overlap } else { // no overlap }
To find the actual overlap range, you take the maximum of the two low ends, and the minimum of the two high ends:
int e = Math.max(a,b); int f = Math.min(c,d); // overlapping range is [e,f], and overlap exists if e <= f.
All above assumes that the ranges are inclusive, that is, the range defined by a
and c
includes both the value of a
and the value of c
. It is fairly trivial to adjust for exclusive ranges, however.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With