Created
June 15, 2015 00:38
-
-
Save VegaFromLyra/78adac39840a1fa06b63 to your computer and use it in GitHub Desktop.
Condense Meeting Times
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://www.interviewcake.com/question/merging-ranges | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace MeetingTimes | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
// Test Case 1 | |
// var input = new TimeBlock[]{ | |
// new TimeBlock(0, 1), | |
// new TimeBlock(3, 5), | |
// new TimeBlock(4, 8), | |
// new TimeBlock(10, 12), | |
// new TimeBlock(9, 10) | |
// }; | |
// Test Case 2 | |
var input = new TimeBlock[] { | |
new TimeBlock(2, 3), | |
new TimeBlock(4, 7), | |
new TimeBlock(5, 8), | |
new TimeBlock(1, 10), | |
}; | |
Console.WriteLine("Input:"); | |
foreach (var item in input) | |
{ | |
Console.Write(item.ToString() + " "); | |
} | |
Console.WriteLine(); | |
var output = condense_meeting_times(input); | |
Console.WriteLine("Output:"); | |
foreach (var item in output) | |
{ | |
Console.Write(item.ToString() + " "); | |
} | |
Console.WriteLine(); | |
} | |
static List<TimeBlock> condense_meeting_times(TimeBlock[] inputTimes) { | |
if (inputTimes.Length < 2) { | |
return inputTimes.ToList(); | |
} | |
Array.Sort(inputTimes); | |
var result = new List<TimeBlock>(); | |
var prev = inputTimes[0]; | |
for(int i = 1; i < inputTimes.Length; i++) { | |
var current = inputTimes[i]; | |
if (canBeMerged(prev, current)) { | |
prev.Start = Math.Min(prev.Start, current.Start); | |
prev.End = Math.Max(prev.End, current.End); | |
} else { | |
result.Add(prev); | |
prev = current; | |
} | |
} | |
result.Add(prev); | |
return result; | |
} | |
// NOTE t1.Start <= t2.Start is given | |
static bool canBeMerged(TimeBlock t1, TimeBlock t2) { | |
return (t1.Start <= t2.Start) && (t2.Start <= t1.End); | |
} | |
} | |
class TimeBlock : IComparable | |
{ | |
public TimeBlock() { | |
} | |
public TimeBlock(int start, int end) { | |
Start = start; | |
End = end; | |
} | |
public int Start {get; set;} | |
public int End {get; set; } | |
public int CompareTo(object other) { | |
var otherTimeBlock = other as TimeBlock; | |
return Start.CompareTo(otherTimeBlock.Start); | |
} | |
public override string ToString() { | |
return String.Format("({0}, {1})", Start, End); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment