fork(1) download
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class Schedule {
  5. public TimeSpan Begin {get;set;}
  6. public TimeSpan End {get;set;}
  7. }
  8. class GalaxySector {
  9. public TimeSpan Begin {get;set;}
  10. public TimeSpan End {get;set;}
  11. }
  12.  
  13. public class Test
  14. {
  15.  
  16. private static readonly TimeSpan HalfHour = TimeSpan.Parse("0:30");
  17.  
  18. private static IEnumerable<Schedule> Group(IList<GalaxySector> all) {
  19. // Protect from division by zero
  20. if (all.Count == 0) {
  21. yield break;
  22. }
  23. // Find initial location
  24. var pos = 0;
  25. while (pos < all.Count) {
  26. var prior = (pos + all.Count - 1) % all.Count;
  27. if (all[prior].End+HalfHour >= all[pos].Begin) {
  28. pos++;
  29. } else {
  30. break;
  31. }
  32. }
  33. pos = pos % all.Count;
  34. // Start grouping items together
  35. var stop = pos;
  36. do {
  37. var start = pos;
  38. var next = (pos+1) % all.Count;
  39. while (next != stop && all[pos].End+HalfHour >= all[next].Begin) {
  40. pos = next;
  41. next = (pos+1) % all.Count;
  42. }
  43. yield return new Schedule {Begin = all[start].Begin, End = all[pos].End};
  44. pos = next;
  45. } while (pos != stop);
  46. }
  47.  
  48. public static void Main()
  49. {
  50. var all = new GalaxySector[] {
  51. new GalaxySector {Begin=TimeSpan.Parse("0:15"), End=TimeSpan.Parse("2:30")}
  52. , new GalaxySector {Begin=TimeSpan.Parse("2:45"), End=TimeSpan.Parse("3:30")}
  53. , new GalaxySector {Begin=TimeSpan.Parse("8:00"), End=TimeSpan.Parse("9:30")}
  54. , new GalaxySector {Begin=TimeSpan.Parse("10:00"), End=TimeSpan.Parse("11:00")}
  55. , new GalaxySector {Begin=TimeSpan.Parse("11:20"), End=TimeSpan.Parse("12:30")}
  56. , new GalaxySector {Begin=TimeSpan.Parse("14:00"), End=TimeSpan.Parse("16:00")}
  57. , new GalaxySector {Begin=TimeSpan.Parse("18:30"), End=TimeSpan.Parse("19:30")}
  58. , new GalaxySector {Begin=TimeSpan.Parse("19:45"), End=TimeSpan.Parse("21:00")}
  59. , new GalaxySector {Begin=TimeSpan.Parse("22:00"), End=TimeSpan.Parse("23:50")}
  60. };
  61. foreach (var sched in Group(all)) {
  62. Console.WriteLine("{0}..{1}", sched.Begin, sched.End);
  63. }
  64. }
  65. }
Success #stdin #stdout 0.07s 24072KB
stdin
Standard input is empty
stdout
08:00:00..12:30:00
14:00:00..16:00:00
18:30:00..21:00:00
22:00:00..03:30:00