How to find an elegant function to determine overlap with multiple (potentially infinitely many) intervals?

20 Views Asked by At

I have two time windows: daytime lasts from 07.00 to 19.00 every day, and nighttime lasts from 19.00 to 7.00 every day. Then I have 'maintenance intervals' with a given start and end time, [s,e]. s and e are real numbers indicating the number of hours since midnight of the very first day. For any maintenance interval, I would like to determine whether it is for the largest part during the day or for the largest part during the night.

Therefore I started to try to determine the total time that a maintenance interval is during daytime and the total time that a maintenance interval is during nighttime, but I cannot find out how to do this nicely.

Some inputs and outputs:

  1. [20, 22] = 2 hours during nighttime, 0 hours during daytime (so this is to be classified as a nighttime maintenance interval)
  2. [10, 25] = 9 hours during daytime, 6 hours during nighttime (daytime maintenance interval)
  3. [10, 49] = 21 hours during daytime, 18 hours during nighttime (daytime maintenance interval)

Observe also the similarity between 2 and 3. The 3rd interval lasts much longer (exactly a day longer than the 2nd), but the result would be the same. Potentially a nice solution can benefit from this characteristic, discarding all 'whole days in between' that do not matter to the eventual solution.

Preferably, I obtain an elegant solution that can be easily displayed in mathematical notation (rather than an entire algorithm).

Hope anyone can help!

1

There are 1 best solutions below

2
On

I think this will work. Given $s$ and $e$ define:

$e'=e-24 \times \lfloor \frac{e - s}{24}\rfloor$

This removes any full days.

Then define

Amount in daytime: $d = min(19:00, e') - max(07:00, s)$

Amount in nighttime: $n = (e' - s) - d$

And compare $d$ and $n$.

Not sure if you'd count this as an "algorithm" or not - you can probably make it a little more compact but I think that would be at the expense of clarity.