Skip to content

Instantly share code, notes, and snippets.

@lenkan
Created October 30, 2016 21:34
Show Gist options
  • Save lenkan/5ade5dcf0a80573928f02348b2bb11d5 to your computer and use it in GitHub Desktop.
Save lenkan/5ade5dcf0a80573928f02348b2bb11d5 to your computer and use it in GitHub Desktop.
using NUnit.Framework;
using System.Collections.Generic;
using System.Linq;
namespace ClassLibrary2
{
[TestFixture]
public class TestFixture
{
[Test]
public void TestInterleave()
{
IEnumerable<string> s1 = new[] {"a", "b", "c"};
IEnumerable<string> s2 = new[] { "1", "2", "3", "4", "5"};
var r1 = s1.Interleave(s2);
Assert.That(r1, Is.EquivalentTo(new []
{
"a", "1", "b", "2", "c", "3", "4", "5"
}));
}
[Test]
public void TestInterleaveWithFirstSequenceLonger()
{
IEnumerable<string> s1 = new[] { "1", "2", "3", "4", "5" };
IEnumerable<string> s2 = new[] { "a", "b", "c" };
var r1 = s1.Interleave(s2);
Assert.That(r1, Is.EquivalentTo(new[]
{
"1", "a","2", "b", "3", "c", "4", "5"
}));
}
[Test]
public void TestInterleaveReverse()
{
IEnumerable<string> s1 = new[] { "a", "b", "c" };
IEnumerable<string> s2 = new[] { "1", "2", "3", "4", "5" };
var r1 = s1.Interleave(s2.Reverse());
Assert.That(r1, Is.EquivalentTo(new[]
{
"a", "5", "b", "4", "c", "3", "2", "1"
}));
}
[Test]
public void TestInterleaveMany()
{
IEnumerable<string> s1 = new[] { "a", "b", "c" };
IEnumerable<string> s2 = new[] { "1", "2", "3", "4", "5", "6" };
IEnumerable<string> s3 = new[] { "x", "y", "z", "w"};
var r1 = s1.InterleaveMany(s2, s3);
Assert.That(r1, Is.EquivalentTo(new[]
{
"a", "1", "x", "b", "2", "y", "c", "3", "z", "4", "w", "5", "6"
}));
}
}
public static class Interleaver
{
public static IEnumerable<T> InterleaveMany<T>(this IEnumerable<T> thisSequence, params IEnumerable<T>[] others)
{
var enumerators = new List<IEnumerator<T>> {thisSequence.GetEnumerator()};
enumerators.AddRange(others.Select(x => x.GetEnumerator()));
bool anyHasValue;
do
{
anyHasValue = false;
foreach (var enumerator in enumerators)
{
bool thisHasValue = enumerator.MoveNext();
anyHasValue = thisHasValue || anyHasValue;
if (thisHasValue)
{
yield return enumerator.Current;
}
}
} while (anyHasValue);
}
public static IEnumerable<T> Interleave<T>(this IEnumerable<T> thisSequence, IEnumerable<T> otherSequence)
{
var thisEnumerator = thisSequence.GetEnumerator();
var otherEnumerator = otherSequence.GetEnumerator();
bool thisHasValue;
bool otherHasvalue;
do
{
thisHasValue = thisEnumerator.MoveNext();
otherHasvalue = otherEnumerator.MoveNext();
if (thisHasValue)
{
yield return thisEnumerator.Current;
}
if (otherHasvalue)
{
yield return otherEnumerator.Current;
}
} while (thisHasValue || otherHasvalue);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment