I am making a complex algorithm in C# in which one step is to compare 2 very large lists of ranges and finding out the overlapping region. I have tried a lot of ways to find them, but m not sure if I am covering all possibilities. Also my algo on this step is taking too long with huge lists.
Example:
range 1 = 1-400
range 2 = 200-600
So when I want to check overlap between these two ranges I should get the answer = 200.
Because total 200 numbers are overlapping between these two ranges. So this is how I want the answer, I want the exact number of integers that are overlapping between two ranges.
Example of Lists:
List1 : 1-400, 401-800, 801-1200 and so on...
List2 : 10240-10276, 10420 10456, 11646-11682 and so on...
Now I have to compare each range of list1 with each range of list2, and find out if a certain range of list1 overlaps with any of the range of list2 and if yes then what is the overlapping answer? These are just sample values for the purposes of understanding.
I only need a simple and most efficient/fast formula to find out the overlap answer between 2 ranges. I can manage the rest of the loop algorithm.
Example formula :
var OverlappingValue = FindOverlapping(range1.StartValue, range1.EndValue,range2.StartValue, range2.EndValue);
and if the two ranges are not overlapping at all, then function must return 0.
PS: I didn't post my code because it's really complicated with a lot of conditions, I only need one simple formula.
If there is any overlapping range ; it must start from the max lower bound to the min upper bound so just use that "formula"
Then just get the number of item in that range by subtracting it's upper bound to it's lower one and add one (to be all inclusive)
Finally if that amount is negative it means that the range weren't overlapping so just get the max between that amount and 0 to handle that case
Edit : Oops C# not VB.Net
int FindOverlapping (int start1, int end1, int start2, int end2)
{
return Math.Max (0, Math.Min (end1, end2) - Math.Max (start1, start2) + 1);
}
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