Grum
Grum

Reputation: 13

C - Given two arrays, how do you find the amount of unique elements of one of the arrays?

I have this code I've been working on that displays values of array1 that are duplicates of array2 and duplicates of other values in array1, but I've been having difficulties calculating the amount of unique values. [sizeOfA, sizeOfB, a[] and b[] are obtained through the main function]

int aDupes = 0;
int bDupes = 0;
int i, j, k;

for(i = 0; i < sizeOfA; i++){
    for(j = 0; j < sizeOfB; j++){
        if(a[i] == b[j]){
            bDupes++;
        }
    } 
} 
for(i = 0; i < sizeOfA; i++){
    for(j = i+1; j < sizeOfA; j++){
        for(k = 0; k < sizeOfB; k++){
            if(a[i] == a[j] && a[i] == b[k]){
                aDupes++;
            }
        }
    }
}

So for example a[] = {1, 3, 3, 5, 6, 7, 8} b[] = {1, 3, 8, 2} would return aDupes = 1 ; bDupes = 4. But the amount of unique elements should be 3 (5, 6, 7). How can I do this?

Upvotes: 1

Views: 124

Answers (2)

Nutan
Nutan

Reputation: 786

int flag=0,unique=0;
for(i = 0; i < sizeOfA; i++){
for(j = i+1; j < sizeOfA; j++){
    for(k = 0; k < sizeOfB; k++){
        if(a[i] != a[j] && a[i] != b[k]){
            flag++;
        }
    }
 }
 if (flag==0){
     unique++;
  } 
 flag=0;
}

This unique variable will give the value of unique elements of the array a

Upvotes: 1

Saurabh Shubham
Saurabh Shubham

Reputation: 43

Use mapping, it is more easy and very clear to understand.

First map all the elements of array2 and check for array1 by also making the map of array 1 and so on.

Upvotes: 0

Related Questions