Created
November 17, 2014 14:19
-
-
Save kashmervil/395c8e40eebc028b8c6f to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Linq; | |
using System.Collections.Generic; | |
namespace Merge | |
{ | |
class Program | |
{ | |
public static IEnumerable<int> Merge(IEnumerable<int> a, IEnumerable<int> b) | |
{ | |
var enumerable1 = a as IList<int> ?? a.ToList(); // Preventing multiple enumeration | |
var enumerable2 = b as IList<int> ?? b.ToList(); | |
var en1 = enumerable1.GetEnumerator(); | |
var en2 = enumerable2.GetEnumerator(); | |
var current1 = (en1.MoveNext()) ? (int?)en1.Current : null; // Using C# advantages for more appropriate interface for current values | |
var current2 = (en2.MoveNext()) ? (int?)en2.Current : null; // e.g checking termination without moving the enumerator's cursor | |
// and "third-party" variables | |
while (current1.HasValue && current2.HasValue) | |
{ | |
while (current1.HasValue && (current1.Value < current2.Value)) | |
{ | |
yield return current1.Value; | |
current1 = (en1.MoveNext()) ? (int?)en1.Current : null; | |
} | |
while (current1.HasValue && current2.HasValue && (current2.Value < current1.Value)) | |
{ | |
yield return current2.Value; | |
current2 = (en2.MoveNext()) ? (int?)en2.Current : null; | |
} | |
if (current1.HasValue && current2.HasValue && (current2.Value == current1.Value)) | |
{ | |
yield return current1.Value; | |
current1 = (en1.MoveNext()) ? (int?)en1.Current : null; | |
current2 = (en2.MoveNext()) ? (int?)en2.Current : null; | |
} | |
} | |
var notEmpty = (current1.HasValue) ? en1 : en2; | |
do yield return notEmpty.Current; while (notEmpty.MoveNext()); | |
} | |
static void Main() | |
{ | |
var list1 = new List<int> {1, 3, 5, 6, 7, 9, 11}; | |
var list2 = new List<int> {1, 2, 4, 6, 8, 9, 10 }; | |
// the result should be something like 1,2,3,4,5,6,7,8,9,10,11 | |
foreach (var i in Merge(list1, list2)) | |
{ | |
Console.WriteLine(i); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment