What's a good, generic algorithm for collapsing a set of potentially-overlapping ranges?

后端 未结 10 2001
执念已碎
执念已碎 2020-12-08 00:28

I have a method that gets a number of objects of this class

class Range
{
    public T Start;
    public T End;
}

In my case

10条回答
  •  有刺的猬
    2020-12-08 01:30

    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 :)

提交回复
热议问题