开发者

If I have two time periods, how do I find out if they overlap? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Determine Whether Two Date Ranges Overlap

Say I have two object开发者_StackOverflow中文版s, and each of these objects have a date ranges which is between its end date and start date, how do I figure out if there is any overlap between the two date ranges in the most efficient or quickest way.

I would like to do this using .NET 3.5 c#


Whether this is the most efficient or quickest, I'm unsure, but this is how I would do it. If it turned out to be a bottleneck, then and only then would I look into optimising further:

You ensure that the first range starts earlier (or at the same time) by swapping the ranges if necessary.

Then, you can detect overlap if the other range start is less than or equal to the first range end (if ranges are inclusive, containing both the start and end times) or less than (if ranges are inclusive of start and exclusive of end).

Assuming inclusive at both ends, there's only four possibilities of which one is a non-overlap:

|----------------------|        range 1
|--->                           range 2 overlap
 |--->                          range 2 overlap
                       |--->    range 2 overlap
                        |--->   range 2 no overlap

The endpoint of the range 2 doesn't enter into it. So, in pseudo-code:

def doesOverlap (r1,r2):
    if r1.s > r2.s:
        swap r1, r2
    if r2.s > r1.e:
        return false
    return true

If the ranges are inclusive at the start and exclusive at the end, you just have to replace > with >= in the second if statement:

|----------------------|        range 1
|--->                           range 2 overlap
 |--->                          range 2 overlap
                       |--->    range 2 no overlap
                        |--->   range 2 no overlap

You greatly limit the number of checks you have to make because you remove half of the problem space early by ensuring range 1 never starts after range 2.


Check wether or not the Startdate or Enddate of the second object is in the range of the first object:

bool overlap = (y.Start > x.Start && y.Start < x.End) || (y.End > x.Start && y.End < x.End);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜