列出时间跨度内所有可能时间跨度的算法

Algorithm listing all possible timespans within a timespan

我在算法实现方面遇到了一些困难。

我有一个开始日期和一个结束日期,我想列出该时间跨度内所有可能的时间跨度,并将特殊条件作为开始日期和结束日期。

例如:

我的开始日期是 01-01-2020,结束日期是 31-01-2020。我的条件是列出所有可能的时间跨度至少有 7 days 和最大 10 days.

所以结果集会是这样的:

01-01-2020 -> 08-01-2020
01-01-2020 -> 09-01-2020
...
02-01-2020 -> 09-01-2020
...
24-01-2020 -> 31-01-2020

最好是 Linq,所以我可以枚举。

这是一个简单的实现。这不是最有效的,但很容易理解:

public static IEnumerable<(DateTime start, DateTime end)> ListTimespans(DateTime startDate, DateTime endDate, int minDays, int maxDays)
{
    // Loop through all of the possible starts. The first day we can start on is startDate,
    // and the last day we can start on is endDate - minDays (which gives us a span
    // minDays long ending on endDate)
    for (var start = startDate; start <= endDate.AddDays(-minDays); start = start.AddDays(1))
    {
        // For each of these starts, loop through the possible end dates. There are two
        // limits to the end date: either hit the maximum number of days for a span
        // (start.AddDays(maxDays)), or we hit the end date.
        // Loop until whichever one comes first.
        for (var end = start.AddDays(minDays); end <= Min(start.AddDays(maxDays), endDate); end = end.AddDays(1))
        {
            yield return (start, end);  
        }
    }
    
    DateTime Min(DateTime x, DateTime y) => x < y ? x : y;
}

查看实际效果 here