using System; using System.Collections.Generic; class Schedule { public TimeSpan Begin {get;set;} public TimeSpan End {get;set;} } class GalaxySector { public TimeSpan Begin {get;set;} public TimeSpan End {get;set;} } public class Test { private static readonly TimeSpan HalfHour = TimeSpan.Parse("0:30"); private static IEnumerable Group(IList all) { // Protect from division by zero if (all.Count == 0) { yield break; } // Find initial location var pos = 0; while (pos < all.Count) { var prior = (pos + all.Count - 1) % all.Count; if (all[prior].End+HalfHour >= all[pos].Begin) { pos++; } else { break; } } pos = pos % all.Count; // Start grouping items together var stop = pos; do { var start = pos; var next = (pos+1) % all.Count; while (next != stop && all[pos].End+HalfHour >= all[next].Begin) { pos = next; next = (pos+1) % all.Count; } yield return new Schedule {Begin = all[start].Begin, End = all[pos].End}; pos = next; } while (pos != stop); } public static void Main() { var all = new GalaxySector[] { new GalaxySector {Begin=TimeSpan.Parse("0:15"), End=TimeSpan.Parse("2:30")} , new GalaxySector {Begin=TimeSpan.Parse("2:45"), End=TimeSpan.Parse("3:30")} , new GalaxySector {Begin=TimeSpan.Parse("8:00"), End=TimeSpan.Parse("9:30")} , new GalaxySector {Begin=TimeSpan.Parse("10:00"), End=TimeSpan.Parse("11:00")} , new GalaxySector {Begin=TimeSpan.Parse("11:20"), End=TimeSpan.Parse("12:30")} , new GalaxySector {Begin=TimeSpan.Parse("14:00"), End=TimeSpan.Parse("16:00")} , new GalaxySector {Begin=TimeSpan.Parse("18:30"), End=TimeSpan.Parse("19:30")} , new GalaxySector {Begin=TimeSpan.Parse("19:45"), End=TimeSpan.Parse("21:00")} , new GalaxySector {Begin=TimeSpan.Parse("22:00"), End=TimeSpan.Parse("23:50")} }; foreach (var sched in Group(all)) { Console.WriteLine("{0}..{1}", sched.Begin, sched.End); } } }