How can I make set complement and set difference in C# without using any collections and Linq?
We have two arrays:
int [] arr1 = new int { 1, 2, 3, 4};
int[] arr2 = new int {3,4,5,6,7,8};
Complement must be: arr3 {5,6,7,8}
and the difference must be: arr4 {1,2}
.
I've tried adding one set to another and then finding duplicates, but couldn't make it.
int numDups = 0, prevIndex = 0;
for (int i = 0; i < array.Length; i++)
{
bool foundDup = false;
for (int j = 0; j < i; j++)
{
if (array[i] == array[j])
{
foundDup = true;
numDups++; // Increment means Count for Duplicate found in array.
break;
}
}
if (foundDup == false)
{
array[prevIndex] = array[i];
prevIndex++;
}
}
// Just Duplicate records replce by zero.
for (int k = 1; k <= numDups; k++)
{
array[array.Length - k] = '\0';
}
You can create two lists, one for complement and other for difference, iterate array A and check which are contained in B and which not and vice-versa, iterate B and check which ones exists in A.
UPDATE: removed lists, used only arrays and no LINQ.