I'm having an issue figuring out a logical way to solve this problem. I have a list of date ranges, say for example:
01/01/15 - 11/01/15
02/01/15 - 04/01/15
09/01/15 - 13/01/15
18/01/15 - 20/01/15
What I need to do is figure out the total number of nights covered over all of these date ranges.
So for the example the total should be 14 nights:
01/01/15 - 11/01/15 // 10 nights
02/01/15 - 04/01/15 // Ignored as nights are covered in 1-11
09/01/15 - 13/01/15 // 2 nights as 11th and 12th nights haven't been covered
18/01/15 - 20/01/15 // 2 nights
I can easily figure out the total number of nights using min-max dates but that ignores the missing dates (14-17 in the example) and is what I can't figure out.
Is there any way to find the total number of days missing to help figure this out?
Here's a way using a HashSet:
This assumes that your date ranges are half-open intervals (i.e. the start date is considered part of the range but the end date is not).
Here's a complete program to demonstrate. The answer is
14
:NOTE: This is NOT very efficient for large date ranges! If you have large date ranges to consider, an approach that combines overlapping ranges into single ranges would be better.
[EDIT] Fixed the code to use half-open intervals rather than closed intervals.