As a follow up to the method that collapses overlapping ranges I thought I would try to create a method that combines adjacent ranges.
Basically, after running the Collapse method you may end up with for example 1 to 5 and 6 to 10. I would like to combine those into one range, 1 to 10.
This is what I have come up with so far, but it doesn’t really work very well. Does anyone spot my problem or have good alternative solution?
public static IEnumerable<Range<T>> MergeAdjacent<T>(this IEnumerable<Range<T>> source, Func<T, T, bool> isAdjacent)
{
using (var sourceIterator = source.GetEnumerator())
{
if (!sourceIterator.MoveNext())
yield break;
var first = sourceIterator.Current;
while (sourceIterator.MoveNext())
{
var second = sourceIterator.Current;
if (isAdjacent(first.End, second.Start))
{
yield return Range.Create(first.Start, second.End);
}
else
yield return first;
first = second;
}
yield return first;
}
}
I’ve reached this solution. One prerequisite is that ranges are ordered ascending/descending depending on the Func. It will merge adjacent ranges and it’s still deferred execution. I didn’t perform a lot of tests so there might be edge cases that break this. Be gentile 🙂
Edit: Shortened down the code a bit. As far as I can see it works. Left out
nullchecks though.