'Improve partitioning algorithm
I was trying to write an algorithm that builds an array of dates ranges using a start and end date and a delta.
In broader terms, the algorithm input and output are as following :
/*
INPUT : T1 of type DateTimeoffset.
T2 of type DateTimeoffset.
delta of type Int.
OUTPUT : An array of time ranges [x, y] where x is start date and y is end date.
R1 = [T1 , T1 + delta * 1]
R2 = [T1 + delta * 1 , T1 + delta * 2]
R3 = [T1 + delta * 2 , T1 + delta * 3]
R4 = [T1 + delta * 3 , T1 + delta * 4]
R5 = [T1 + delta * 4 , T1 + delta * 5]
R6 = [T1 + delta * 5 , T2]
*/
The C# code I built for this is as following:
public static (DateTimeOffset From, DateTimeOffset To)[] Partition(DateTimeOffset start, DateTimeOffset end, int delta)
{
var ranges = new List<(DateTimeOffset From, DateTimeOffset To)>();
var lower = start;
var offset = 0;
while (lower < end)
{
var lowerbound = start + TimeSpan.FromMinutes(delta * offset);
var upperbound = start + TimeSpan.FromMinutes(delta * ++offset);
if(upperbound > end)
upperbound = end;
ranges.Add((From: lowerbound, To: upperbound));
lower = upperbound;
}
return ranges.ToArray();
}
is there a better way to write this algorithm and if not how can it be improved ?
Solution 1:[1]
Seems like you don't need to multiply the offset each time, just keep track of the previous upper bound:
public static (DateTimeOffset From, DateTimeOffset To)[] Partition(DateTimeOffset start, DateTimeOffset end, int delta)
{
var ranges = new List<(DateTimeOffset From, DateTimeOffset To)>();
var lowerbound = start;
while (lowerbound < end)
{
var upperbound = lower + TimeSpan.FromMinutes(delta);
if(upperbound > end) upperbound = end;
ranges.Add((From: lowerbound, To: upperbound));
lowerbound = upperbound;
}
return ranges.ToArray();
}
Other options:
- Do you need to return an array? Could you just return the list or an
IEnumerableand avoid the (relatively cheap) conversion to an array? - You could use
yieldto return values as they are computed, but the only benefit is if a consumer doesn't need the entire list and can stop the generation before it reaches the end.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | D Stanley |
