How to combine overlapping time ranges (time ranges union)

后端 未结 10 1374
渐次进展
渐次进展 2020-12-08 05:19

I have an array with several time ranges inside:

[Tue, 24 May 2011 08:00:00 CEST +02:00..Tue, 24 May 2011 13:00:00 CEST +02:00,
 Tue, 24 May 2011 16:30:00 CE         


        
10条回答
  •  太阳男子
    2020-12-08 05:51

    Searching a little bit I have found a code that does the trick:

    def self.merge_ranges(ranges)
      ranges = ranges.sort_by {|r| r.first }
      *outages = ranges.shift
      ranges.each do |r|
        lastr = outages[-1]
        if lastr.last >= r.first - 1
          outages[-1] = lastr.first..[r.last, lastr.last].max
        else
          outages.push(r)
        end
      end
      outages
    end
    

    A sample (working with time ranges too!):

    ranges = [1..5, 20..20, 4..11, 40..45, 39..50]
    merge_ranges(ranges)
    => [1..11, 20..20, 39..50]
    

    Found here: http://www.ruby-forum.com/topic/162010

提交回复
热议问题