BlackMatrix
BlackMatrix

Reputation: 504

Algorithm listing all possible timespans within a timespan

I'm struggeling a bit with an algorithm implementation.

I am having a start date and an end date and I want to list all possible timespans within that timespan with a special condition as start and end dates.

For example:

My start date is 01-01-2020 and my end date is 31-01-2020. My condition is to list all possible timespans that have at least 7 days and maximum 10 days.

So the result set would be like:

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

Preferable as Linq so I can enumerate.

Upvotes: 1

Views: 91

Answers (1)

canton7
canton7

Reputation: 42245

Here's a simple implementation. It's not the most efficient, but it's easy to understand:

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;
}

See it in action here.

Upvotes: 2

Related Questions