I have a number of range objects that I need to combine so that all overlapping ranges disappear:
case class Range(from:Int, to:Int) val rangelist = List(Range(3, 40), Range(1, 45), Range(2, 50), etc)
The ranges below are:
3 40 1 45 2 50 70 75 75 90 80 85 100 200
Upon completion, we will receive:
1 50 70 90 100 200
Imperative Algorithm:
- Pop () the first range-obj and iterate over the rest of the list, comparing it with each of the other ranges.
- if there is an overlapping element, merge them together (this gives a new Range instance) and remove 2 merge lists from the original list.
- At the end of the list, add a Range object (which could change several times by merging) in the final list of results.
- Repeat this with the next remaining item.
- Once the source list is empty, we are done.
To do this, you need to create many temporary variables, indexed loops, etc.
So, I wonder if there is a more functional approach?
At first glance, the source compilation should be able to act as a stack in providing pop () PLUS, providing the ability to delete items by index during iteration over it, but then it will no longer function.
recalcitrant
source share