Multiple Date range comparison for overlap: how to do it efficiently?
To find if all are overlapping
static bool Overlap(params Tuple<DateTime, DateTime>[] ranges)
{
for (int i = 0; i < ranges.Length; i++)
{
for (int j = i + 1; j < ranges.Length; j++)
{
if (!(ranges[i].Item1 <= ranges[j].Item2 && ranges[i].Item2 >= ranges[j].Item1))
return false;
}
}
return true;
}
to find if any are overlapping
static bool Overlap(params Tuple<DateTime, DateTime>[] ranges)
{
for (int i = 0; i < ranges.Length; i++)
{
for (int j = i + 1; j < ranges.Length; j++)
{
if (ranges[i].Item1 <= ranges[j].Item2 && ranges[i].Item2 >= ranges[j].Item1)
return true;
}
}
return false;
}
Try this:
private bool intersects(DateTime r1start, DateTime r1end,
DateTime r2start, DateTime r2end)
{
return (r1start == r2start)
|| (r1start > r2start ?
r1start <= r2end : r2start <= r1end);
}
If I'm understanding correctly, you want to answer the question: Are there any two of these ranges that overlap? Sort them according to their left-hand end, and then go through looking to see if 1 overlaps 2, if 2 overlaps 3, etc. If there is any overlap, this will find it. I don't believe there is any way to answer your question for an arbitrary list of intervals without taking at least O(n log n) time, which is what sorting them will cost you.
Alternatively, perhaps you want to answer the question: Are there any two of these ranges that don't overlap? (On the face of it that's what your edited question is asking, but (1) that seems like a strange thing to want and (2) your comment above seems to indicate that it's not what you mean.) To check for this, find the interval with the leftmost right-hand end and the interval with the rightmost left-hand end, and see whether they overlap. (If any two of your intervals don't overlap, these two don't.)