Search code examples
c++carraysunique

C/C++ How can I get unique value from 2 arrays?


I need to get the unique value from 2 int arrays

Duplicate is allowed

There is just one unique value

like :

int arr1[3]={1,2,3};
int arr2[3]={2,2,3};

and the value i want to get is :

int unique[]={1}

how can i do this? im already confused in my 'for' and 'if' this was not homework

i know how to merge 2 arrays and del duplicate values

but i alse need to know which array have the unique value

plz help me :)

and here is some code i did

int arr1[3]={1,2,3}
int arr2[3]={2,2,3}
int arrunique[1];
bool unique = true;
for (int i=0;i!=3;i++)
{

    for (int j=0;j!=3;j++)
    {
    if(arr1[i]==arr2[j])
    {
        unique=false;
        continue;
    }
    else 
    {
        unique=true;
    }
if(unique)
{
arrunique[0]=arr1[i]
break;
}
}

cout << arrunique[0];

Solution

  • Assuming:

    • You have two arrays of different length,
    • The arrays are sorted
    • The arrays can have duplicate values in them
    • You want to get the list of values that only appear in one of the arrays
      • including their duplicates if present

    You can do (untested):

    // Assuming arr1[], arr2[], and lengths as arr1_length  
    int i = 0,j = 0, k = 0;
    int unique[arr1_length + arr2_length];
    
    while(i < arr1_length && j < arr2_length) {
       if(arr1[i] == arr2[j]) {
         // skip all occurrences of this number in both lists
         int temp = arr1[i];
         while(i < arr1_length && arr1[i] == temp) i++;
         while(j < arr2_length && arr2[j] == temp) j++;
       } else if(arr1[i] > arr2[j]) {
         // the lower number only occurs in arr2
         unique[k++] = arr2[j++]; 
       } else if(arr2[j] > arr1[i]) {
         // the lower number only occurs in arr1
         unique[k++] = arr1[i++]; 
       }     
    }
    
    while(i < arr1_length) {
       // if there are numbers still to read in arr1, they're all unique
       unique[k++] = arr1[i++];
    }
    while(j < arr2_length) {
       // if there are numbers still to read in arr2, they're all unique
       unique[k++] = arr2[j++];
    }
    

    Some alternatives:

    • If you don't want the duplicates in the unique array, then you can skip all occurrences of this number in the relevant list when you assign to the unique array.

    • If you want to record the position instead of the values, then maintain two arrays of "unique positions" (one for each input array) and assign the value of i or j to the corresponding array as appropriate.

    • If there's only one unique value, change the assignments into the unique array to return.