Created
June 8, 2018 19:58
-
-
Save discosultan/cb73466c6d2e182fb49adf6a50674756 to your computer and use it in GitHub Desktop.
interval merging
This file contains 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
using static System.Diagnostics.Debug; | |
using static System.Math; | |
using Intervals = System.Collections.Generic.List<(int Start, int End)>; | |
namespace ConsoleApp2 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Setup. | |
var input = new Intervals { (1, 4), (8, 10), (3, 6) }; | |
var output = new Intervals(); | |
var expectedOutput = new Intervals { (1, 6), (8, 10) }; | |
// Sort. | |
input.Sort((a, b) => a.Start.CompareTo(b.Start)); | |
// Merge. | |
(int Start, int End)? mergedInterval = null; | |
foreach (var interval in input) | |
{ | |
if (mergedInterval == null) | |
{ | |
mergedInterval = interval; | |
} | |
else if (interval.Start > mergedInterval.Value.End) | |
{ | |
output.Add(mergedInterval.Value); | |
mergedInterval = interval; | |
} | |
else | |
{ | |
mergedInterval = ( | |
mergedInterval.Value.Start, | |
Max(mergedInterval.Value.End, interval.End) | |
); | |
} | |
} | |
if (mergedInterval.HasValue) | |
output.Add(mergedInterval.Value); | |
// Assert. | |
Assert(expectedOutput.Count == output.Count); | |
for (int i = 0; i < output.Count; i++) | |
Assert(expectedOutput[i] == output[i]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment