Hi,
Could someone please help with the following?
I'm not a C#-programmer and would like to get the code below working.
How could I call MergeShuffle<T> in this case.
Thank you very much in advance,
Kind Regards,
Shurik.
Could someone please help with the following?
I'm not a C#-programmer and would like to get the code below working.
How could I call MergeShuffle<T> in this case.
Thank you very much in advance,
Kind Regards,
Shurik.
C#:
using System;
using System.Collections.Generic;
namespace ShuffleLists
{
class Program
{
static void Main(string[] args)
{
List<Int16> lista = new List<Int16>();
lista.Add(1);
lista.Add(3);
lista.Add(5);
lista.Add(7);
List<Int16> listb = new List<Int16>();
listb.Add(2);
listb.Add(4);
listb.Add(6);
listb.Add(8);
// how would I call MergeShuffle<T> with the above 2 lists, please?
//var list_merged = MergeShuffle(lista,listb);
}
//courtesy of https://stackoverflow.com/questions/11296810/how-do-i-implement-ienumerablet
static IEnumerable<T> MergeShuffle<T>(IEnumerable<T> lista, IEnumerable<T> listb)
{
var first = lista.GetEnumerator();
var second = listb.GetEnumerator();
var rand = new Random();
bool exhaustedA = false;
bool exhaustedB = false;
while (!(exhaustedA && exhaustedB))
{
bool found = false;
if (!exhaustedB && (exhaustedA || rand.Next(0, 2) == 0))
{
exhaustedB = !(found = second.MoveNext());
if (found)
yield return second.Current;
}
if (!found && !exhaustedA)
{
exhaustedA = !(found = first.MoveNext());
if (found)
yield return first.Current;
}
}
}
}