c# – Algorithm to detect overlapping periods

c# – Algorithm to detect overlapping periods

Simple check to see if two time periods overlap:

bool overlap = a.start < b.end && b.start < a.end;

or in your code:

bool overlap = tStartA < tEndB && tStartB < tEndA;

(Use <= instead of < if you change your mind about wanting to say that two periods that just touch each other overlap.)

There is a wonderful library with good reviews on CodeProject: http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET

That library does a lot of work concerning overlap, intersecting them, etc. Its too big to copy/paste all of it, but Ill see which specific parts which can be useful to you.

c# – Algorithm to detect overlapping periods

You can create a reusable Range pattern class :

public class Range<T> where T : IComparable
    readonly T min;
    readonly T max;

    public Range(T min, T max)
        this.min = min;
        this.max = max;

    public bool IsOverlapped(Range<T> other)
        return Min.CompareTo(other.Max) < 0 && other.Min.CompareTo(Max) < 0;

    public T Min { get { return min; } }
    public T Max { get { return max; } }

You can add all methods you need to merge ranges, get intersections and so on…

Leave a Reply

Your email address will not be published.