Search code examples
c#setset-operations

Set operations (complement and difference)


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';             
}

Solution

  • 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.

    int[] arr1 = new int[]{ 1,2,3,4 };
    int[] arr2 = new int[]{ 3,4,5,6,7,8 };
    
    //We allocate the max possible size for each array, just for sanity
    int[] arr3 = new int[arr1.Length + arr2.Length];
    int[] arr4 = new int[arr1.Length + arr2.Length];
    
    int difIndex = 0;
    int compIndex = 0;
    
    //Compute difference 
    foreach(int i in arr1)
    {
        bool found = false;
        foreach(int i2 in arr2)
        {
            if(i == i2)
            {
                found = true;
                break;
            }
        }
    
        if(!found)
            arr4[difIndex++] = i;
    }
    
    //Compute complement
    foreach(int i in arr2)
    {
        bool found = false;
        foreach(int i2 in arr1)
        {
            if(i == i2)
            {
                found = true;
                break;
            }
        }
    
        if(!found)
            arr3[compIndex++] = i;
    }
    
    //Remove unused items from array
    Array.Resize(ref arr3, compIndex);
    Array.Resize(ref arr4, difIndex);