I have a method that gets a number of objects of this class
class Range
{
public T Start;
public T End;
}
In my case
The idea of collapsing a list just screamed out "reduce" to me. It didn't end up quite as elegant as I had hoped though.
def collapse(output,next_range):
last_start,last_end = output[-1]
next_start, next_end = next_range
if (next_start <= last_end):
output[-1] = (last_start, max(next_end, last_end))
else:
output.append(next_range)
return output
ranges = [
(11, 15),
(3, 9),
(12, 14),
(13, 20),
(1, 5)]
ranges.sort()
result = [ranges.pop(0)]
reduce(collapse, ranges,result)
print result
thanks to yairchu for typing in the data so I could cut and paste it :)