问题计算重叠的日期范围范围、日期、问题

2023-09-11 03:51:12 作者:易燃易爆

我有一个问题,试图找出正确的算法来计算一组日期范围。

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 of start and end times) and I want to consolidate this list so it does not contains overlapping times.

基本上巩固两个日期范围:

Basically to consolidate two date ranges:

if start1 <= end2 and start2 <= end1 //Indicates overlap
   if start2 < start1 //put the smallest time in start1
      start1 = start2
   endif
   if end2 > end1 //put the highest time in end1
      end1 = end2
   endif
endif

本加入了两个日期时间。

This joins the two date times.

我打了一个绊脚石,当谈到在所有的值迭代,以便最终名单只包含值而不是重叠的。

I hit a stumbling block when it comes to iterating through all the values so the end list only contains values which are not overlapping.

我的功能和递归编程是一个有点生疏和任何帮助将受到欢迎。

My functional and recursive programming is a bit rusty and any help would be welcome.

推荐答案

不要看的时间间隔,只看他们的目的。

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.

现在需要一个计数器置零和你在一起,和走在列表中。当你看到一个红色的时刻,增加计数器。当你看到一个蓝色的时刻,递减计数器。当计数器的值从0到1,输出开始和当前的时间。当计数器值从1变为0,输出端和当前时间。如果计数器值低于0,则输出休斯敦,我们有麻烦了。您应该结束了与你的柜台0和一帮不错的非重叠的时间间隔。

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.

插图。

 A bunch of overlapping intervals:

 (-------------------) 
                       (----------------------)           
                                                          (---)
       (---------------------)                       
                                                     (-----------------)

 A bunch of interval ends:

 (-----(-------------)-(-----)----------------)      (----(---)--------)