public void TestOrder() { var first = new Interval(7, 1); var second = new Interval(5, 3); var sorted = Intervals.Order(new Interval[] { second, first }); Assert.AreEqual(2, sorted.Count); Assert.ReferenceEquals(first, sorted[0]); Assert.ReferenceEquals(second, sorted[1]); }
public void TestMerge() { var first = new Interval(5, 1); var second = new Interval(9, 3); var third = new Interval(12, 7); var merged = Intervals.Merge(new Interval[] { second, third, first }); Assert.AreEqual(1, merged.Count); Assert.AreEqual(first.a, merged[0].a); Assert.AreEqual(third.b, merged[0].b); }
/// <summary> /// If intervals intersect, returns a new merged interval. Otherwise, returns null. /// </summary> /// <param name="i1"></param> /// <param name="i2"></param> /// <returns></returns> public static Interval MergeTwo(Interval i1, Interval i2) { // order intervals var first = i1.a <= i2.a ? i1 : i2; var next = (first == i1) ? i2 : i1; // do intervals intersect? if(next.a >= first.a && next.a <= first.b) return new Interval(first.a, Math.Max(first.b, next.b)); return null; }
public static List<Interval> Merge(IEnumerable<Interval> intervals) { var result = new List<Interval>(); Interval prev = null; foreach(var curr in Order(intervals)) { if(prev == null) { prev = new Interval(curr); continue; } var merged = MergeTwo(prev, curr); if(merged == null) { result.Add(prev); prev = curr; } else prev = merged; } if(prev != null) result.Add(prev); return result; }
public Interval(Interval clone) { a = clone.a; b = clone.b; }