Ben Fidge <be*******@btopenworld.com> wrote:
I would be very interested to see how you approach this as my implementation
is returning duplicate entries in the result list. I found an example in
Java at the following site:
http://www.cs.sjsu.edu/faculty/fecte...ListMerge.html
with the actual Java code as follows:
http://www.cs.sjsu.edu/faculty/fecte...mainCS46B.html
If you have time, could I take you up on the offer of some sample code.
Sure. This example doesn't keep track of which element came from where, but
that's very easy to do by making each element of the new list an object
containing the original element and an enum value.
Let me know if you have any problems with the code below:
using System;
using System.Collections;
public class Test
{
public static void Main()
{
ArrayList a = new ArrayList (new object[]
{"ant", "attack", "bee",
"car", "frog",
"joke", "rage", "tree"});
ArrayList b = new ArrayList (new object[]
{"bar", "car", "ear",
"got", "joke", "smoke"});
IList merged = Merge (a, b);
foreach (string x in merged)
{
Console.WriteLine (x);
}
}
static IList Merge (IList a, IList b)
{
IList ret = new ArrayList();
IEnumerator enumA = a.GetEnumerator();
IEnumerator enumB = b.GetEnumerator();
enumA.Reset();
enumB.Reset();
bool aValid, bValid;
IComparable aElt = GetNext (enumA, out aValid);
IComparable bElt = GetNext (enumB, out bValid);
while (aValid && bValid)
{
int comp = aElt.CompareTo (bElt);
if (comp < 0)
{
ret.Add (aElt);
aElt = GetNext (enumA, out aValid);
}
else if (comp==0)
{
// No need to add both aElt and bElt,
// as they're the same
ret.Add (aElt);
aElt = GetNext (enumA, out aValid);
bElt = GetNext (enumB, out bValid);
}
else
{
ret.Add (bElt);
bElt = GetNext (enumB, out bValid);
}
}
while (aValid)
{
ret.Add (aElt);
aElt = GetNext (enumA, out aValid);
}
while (bValid)
{
ret.Add (bElt);
bElt = GetNext (enumB, out bValid);
}
return ret;
}
static IComparable GetNext (IEnumerator enumerator,
out bool valid)
{
valid = enumerator.MoveNext();
return valid ? (IComparable) enumerator.Current : null;
}
}
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too