Problem calculating overlapping date ranges

前端 未结 2 996
渐次进展
渐次进展 2020-12-15 01:17

I have a problem trying to work out the correct algorithm to calculate a set of date ranges.

Basically I have a list of unordered date ranges (List containing arrays

相关标签:
2条回答
  • 2020-12-15 02:01

    n.m.'s answer is all you will need but if you want to use the code you've already made then simply sort the ranges by the start time and walk through the list merging overlaps.

    0 讨论(0)
  • 2020-12-15 02:05

    Do not look at the intervals, look only at their ends.

    You have a bunch of starting moments and a bunch of ending moments. Imagine that starting moments are red and ending moments are blue. Or imagine that starting moments are opening braces and ending moments are closing braces.

    Put them all together in a list. Sort the list from earliest to latest, ignoring the colour.

    Now take a counter set to zero with you, and walk down the list. When you see a red moment, increment the counter. When you see a blue moment, decrement the counter. When the counter value goes from 0 to 1, output "start" and the current time. When the counter value goes from 1 to 0, output "end" and the current time. If the counter value drops below 0, output "Houston, we have a problem". You should end with your counter at 0 and a bunch of nice non-overlapping intervals.

    This is the good old brace counting algorithm.

    Illustration.

     A bunch of overlapping intervals:
    
     (-------------------) 
                           (----------------------)           
                                                              (---)
           (---------------------)                       
                                                         (-----------------)
    
     A bunch of interval ends:
    
     (-----(-------------)-(-----)----------------)      (----(---)--------)
    
    0 讨论(0)
提交回复
热议问题