private bool StartsBeforeDisjoint(Interval a, Interval b) { return(a.Start < b.Start && !a.IntersectsWith(b)); }
private static bool StartsAfterNonDisjoint(Interval a, Interval b) { return(a.Start >= b.Start && a.IntersectsWith(b)); }
/** Return a new set with the intersection of this set with other. Because * the intervals are sorted, we can use an iterator for each list and * just walk them together. This is roughly O(min(n,m)) for interval * list lengths n and m. */ public IntervalSet Intersect(IntervalSet other) { if (other == null) { return(new IntervalSet()); } var myIntervals = this.intervals; var theirIntervals = ((IntervalSet)other).intervals; IntervalSet intersection = new IntervalSet(); int mySize = myIntervals.Count; int theirSize = theirIntervals.Count; int i = 0; int j = 0; // iterate down both interval lists looking for nondisjoint intervals while (i < mySize && j < theirSize) { Interval mine = myIntervals[i]; Interval theirs = theirIntervals[j]; //[email protected]("mine="+mine+" and theirs="+theirs); if (StartsBeforeDisjoint(mine, theirs)) { // move this iterator looking for interval that might overlap i++; } else if (StartsBeforeDisjoint(theirs, mine)) { // move other iterator looking for interval that might overlap j++; } else if (mine.Contains(theirs)) { // overlap, add intersection, get next theirs intersection.Intervals.Add(theirs); j++; } else if (theirs.Contains(mine)) { // overlap, add intersection, get next mine intersection.Intervals.Add(mine); i++; } else if (mine.IntersectsWith(theirs)) { // overlap, add intersection intersection.AddImpl(mine.Intersection(theirs).Value); // Move the iterator of lower range [a..EndInclusive], but not // the upper range as it may contain elements that will collide // with the next iterator. So, if mine=[0..115] and // theirs=[115..200], then intersection is 115 and move mine // but not theirs as theirs may collide with the next range // in thisIter. // move both iterators to next ranges if (StartsAfterNonDisjoint(mine, theirs)) { j++; } else if (StartsAfterNonDisjoint(theirs, mine)) { i++; } } } return(intersection); }