The difference between collections A
and B
are all elements in A
that are not in B
. The compliment between those collections are all elements in B
that are not in A
. These are mirror definitions, so you really only need to write a method for difference and then have the compliment method call the difference method with the input parameters reversed.
(Well, strictly speaking, the compliment is all elements anywhere that are not in A
, but that distinction is irrelevant here.)
// Get an array of all elements in b that are not in a
// This is identical to calling GetDifference with the inputs reversed so lets just do that
int[] GetCompliment(int[] a, int[] b) { return GetDifference(b, a); }
// Get an array of all elements in a that are not in b
int[] GetDifference(int[] a, int[] b)
{
// Create the buffer array at the worst-case length which is the length
// of a (where none of the elements in a are in b)
int[] c = new int[a.Length];
// Track how many elements we are actually ending up with
int length = 0;
// Loop through every element in a
foreach (var ax in a)
{
bool found = false;
// Loop through every element in b to see if it exists in a
foreach (var bx in b)
{
if (ax == bx)
{
// If the element was found in b, there's no reason to keep looping
found = true;
break;
}
}
// Only save the element if it was not found in b
if (!found)
{
c[length] = ax;
length++;
}
}
// Create the result array using the length of actual elements found
int[] result = new int[length];
// Copy the relevant slice of the buffer array into the result array
Array.Copy(c, result, length);
// Return the result array
return result;
}
Usage:
int[] a = { 1, 2, 3, 4 };
int[] b = { 3, 4, 5, 6, 7, 8 };
int[] c = GetDifference(a, b);
foreach(var cx in c)
{
Console.Write(cx + ", ");
}
Console.WriteLine();
int[] d = GetCompliment(a, b);
foreach(var dx in d)
{
Console.Write(dx + ", ");
}
// Output:
// 1, 2,
// 5, 6, 7, 8
DotNetFiddle