0

I am trying to find the reverse intersection to see if two teams can play each other but having a hard time figuring out the precise code to do it.

The class represtenting the ranges below would contain two properties, a start time and end time which can be date time or timespan. Each team can have a list of these. The timespan property goes down to the minute so 2:21 pm is valid.

Team 1 can't play between those two times listed, so they can only play from 10:00 AM-5:00 PM. We store the exclusion though.

Team 2 can play 8:00 AN -12:00 PM.

Meaning Team 1 and Team 2 can play between 10-12. Is there a good way to calculate this out in code?

Team 1

List<Restriction>
     Restriction
          StartTime: 8:00 AM
          EndTime: 10:00 AM
     Restriction
          StartTime: 5:00 PM
          EndTime: 9:00 PM

Team 2

List<Restriction>
     Restriction
          StartTime: 12:00 PM
          EndTime: 9:00 PM
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341
  • Sorry, I am confused with the time notation. – mtmk Sep 27 '14 at 01:16
  • Just typing out loud here, but I'm thinking you could turn all hours in the day to bits in a byte array where playable hours are 1's, then do AND operation between teams. What shakes out would be times they could play each other. – Crowcoder Sep 27 '14 at 01:36
  • if you convert your times to when they can play (even temporarily) and then convert it to a collection of available hours, it becomes an intersection instead of a reverse intersection. – Peter Ritchie Sep 27 '14 at 01:52
  • I like the idea of the bit comparison but what if you can go down to the minute. – Mike Flynn Sep 27 '14 at 02:16

1 Answers1

1

Make an array of all the start and end times, including a +1 or a -1 depending whether each time is a start or end time.

For your set of times, this gives you:

[(08:00, +1), (10:00, -1), (17:00, +1), (21:00, -1), (12:00, +1), (21:00, -1)]

Sort them:

[(08:00, +1), (10:00, -1), (12:00, +1), (17:00, +1), (21:00, -1), (21:00, -1)]

Do a running sum of the plus and minus 1's:

[(08:00, 1), (10:00, 0), (12:00, 1), (17:00, 2), (21:00, 1), (21:00, 0)]

The running sum is the number of teams (0, 1 or 2) which are busy starting at that time. So times which are now labelled with a 0 are the start time when both teams are free (here 10:00 and 21:00). The next time in the array is the end of the free period. This gives the time periods when both teams are free, which including the ones at the start and end are (-infinity to 08:00), (10:00 to 12:00) and (21:00 to +infinity).

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118
  • Interesting. I will try this out. Looks exactly what I needed and would of never thought if that. How did you come up with that? – Mike Flynn Sep 27 '14 at 12:37
  • How would you handle two teams with 10AM-3PM and 12-9? Do I need to include a infinity -10? – Mike Flynn Sep 28 '14 at 16:02