How to make calculation on time intervals?

后端 未结 5 686
逝去的感伤
逝去的感伤 2021-01-07 23:09

I have a problem ,i solve it but i have written a long procedure and i can\'t be sure that it covers all the possible cases .

The problem:

If i have a

5条回答
  •  再見小時候
    2021-01-07 23:35

    I found out probably the simplest solution.

    .netFiddle

    1. Sort "Secondary intervals" by start date.
    2. Look for gaps in "secondary intervals" (simple iteration)
    3. Compare gaps with "main interval".

          //declare intervals
      var secondryIntervals = new List> {
              new Tuple( new DateTime(2015, 03, 15, 4, 0, 0), new DateTime(2015, 03, 15, 5, 0, 0)),
              new Tuple( new DateTime(2015, 03, 15, 4, 10, 0), new DateTime(2015, 03, 15, 4, 40, 0)),
              new Tuple( new DateTime(2015, 03, 15, 4, 40, 0), new DateTime(2015, 03, 15, 5, 20, 0))};
      var mainInterval = new Tuple(new DateTime(2015, 03, 15, 3, 0, 0), new DateTime(2015, 03, 15, 7, 0, 0));
      // add two empty intervals before and after main interval
      secondryIntervals.Add(new Tuple(mainInterval.Item1.AddMinutes(-1), mainInterval.Item1.AddMinutes(-1)));
      secondryIntervals.Add(new Tuple(mainInterval.Item2.AddMinutes(1), mainInterval.Item2.AddMinutes(1)));
      secondryIntervals = secondryIntervals.OrderBy(s => s.Item1).ToList();
      // endDate will rember 'biggest' end date
      var endDate = secondryIntervals.First().Item1;
      var result = secondryIntervals.Select(s =>
      {
          var temp = endDate;
          endDate = endDate < s.Item2 ? s.Item2 : endDate;
          if (s.Item1 > temp)
          {
              return new Tuple(temp < mainInterval.Item1 ? mainInterval.Item1 : temp,
                                                   mainInterval.Item2 < s.Item1 ? mainInterval.Item2 : s.Item1);
          }
          return null;
      })
          // remove empty records
                      .Where(s => s != null && s.Item2 > s.Item1).ToList();
      var minutes = result.Sum(s => (s.Item2 - s.Item1).TotalMinutes);
      

    The algorithm requires O(n log n) time (for sorting) without additional storage and assumptions.

提交回复
热议问题