Problem Solving: Difference between Sets
Learn how to calculate the difference between sets.
We'll cover the following
In this lesson, we’ll compute the difference of two sets where the difference set AB
is the set of all elements that are in A
but not in B
.
For example, if A
= {1, 4, 7} and B
= {7, 8}, then AB
= {1, 4}.
In this case, element 7 is present in both A
and B
, so it is not included in AB
.
So the resulting set only includes elements 1 and 4, which are unique to set A
.
Instruction: Use the following playground to write the complete code for the task in this lesson.
We have already added code for loading, sorting, and displaying sets, so you do not need to include that.
// We have hidden deliberately the loading// and sorting and displaying part so that we can focus only// on computing AB and BA sets.{/*Assume you haveA, sizeA, B, sizeBsets are available, and both are sorted now.*/// Write code here for computing AB// Write code for displaying the AMinusB// Write code here for computing BA// Write code for displaying the BMinusA}
Difference between sets
Task: Compute the difference between the two sets A
and B
.
We want to print the set differences between A
and B
(both AB
and BA
). Again, first, we should store this difference in a third set and then print it. For example, for the sets A
and B
given above, the program should print:
Sample output:
A[] = {2 3 4 5 10}
B[] = {2 3 4 7 8 10}
A – B = {5}
B – A = {7,8}
The general idea is the following:
 For every element $e$ of the first set, if we cannot find it in the second set, we will add that element to the difference set.
Look at the animation below to understand the algorithm:
Implementing $A  B$
Let’s write down a code for both cases starting with AB
:
// Case:1 ABint AMinusB[500];bool found;int mi = 0;for (int ai = 0; ai <= sizeA  1; ai++){found = false;for (int bi = 0; bi <= sizeB  1; bi++){if (A[ai] == B[bi]){found = true; break;}}if (!found){AMinusB[mi] = A[ai];mi++;}}// Print the case:1 ABint minusSize = mi;cout << "\nA  B: = {";for (int mi = 0; mi <= minusSize  1; mi++){cout << AMinusB[mi];if (mi != minusSize  1)cout << ", ";}cout << "}";

Lines 5–20: For every element of set
A
, we search it in setB
. If it’s notfound
, we add that element intoAminusB
. 
Line 22–30: We print the set
AminusB
on a console.
Exercise: Compute BA
Write the code for computing BA
and print it.
Instruction: Add the above code in the playground and enable the program to compute the set differences for both AB
and BA
.