A
collections和B
are all elements in A
that are not in的区别B
。这些集合之间的恭维是所有B
不在的元素A
。这些是镜像定义,所以你真的只需要写一个差分方法,然后让恭维方法调用差分方法,输入参数反转。
(好吧,严格来说,恭维是所有不在 中的元素,但A
这种区别在这里无关紧要。)
// 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;
}
用法:
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
点网提琴