Problem Solving: Difference between Sets (Using Functions)
Explore how to implement set difference operations between two arrays using functions in C++. Learn to create reusable setMinus() and isPresent() functions to efficiently find elements in one set that are not present in another, improving code modularity and clarity.
We'll cover the following...
Difference between sets
Let’s make two functions:
void setMinus(int A1[ ], int sizeA1,int A2[ ], int sizeA2,int R[ ], int &sizeR)
In the setMinus function, we have the following six parameters:
- The first parameter is set
A1[]. - The second parameter is set
sizeA1. - The third parameter is set
A2. - The fourth parameter is set
sizeA2. - The fifth parameter is
R[], which stores the result of difference (the elements ofA1that are not present in setA2). - The last parameter is the size of the
R[]set,sizeR, which will be passed by reference.
This function will call the isPresent() function and check if an element A1[ai] of set A1 is not present in set A2. If not present, it’ll simply add it into R[] and increment the count maintained in mi.
Let’s compare the two implementations:
Difference between sets (implementation with and without functions)
The previous implementation:
// A-B algorithm
int 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++;
}
}
// **Set B-A algorithm**
int BMinusA[500];
mi = 0;
bool present;
for (int bi = 0; bi <= sizeB - 1; bi++)
{
present = false;
for (int ai = 0; ai <= sizeA - 1; ai++)
{
if (B[bi] == A[ai])
{
present=true;
break;
}
}
if (!present)
{
BMinusA[mi] = B[bi];
mi++;
}
}
Implementation with functions:
void setMinus(int A1[ ], int sizeA1,
int A2[ ], int sizeA2,
int R[ ], int &sizeR)
{
bool found;
int mi = 0;
for (int ai = 0; ai <= sizeA1-1; ai++)
{
if(!isPresent(A2, sizeA2, A1[ai]))
{
R[mi] = A1[ai];
mi++;
}
}
sizeR = mi;
}
Call functions from main:
.
.
.
setMinus(A, sizeA, B, sizeB,
AMinusB, minusSize);
setPrint("A-B", AMinusB, minusSize);
setMinus(B, sizeB, A, sizeA,
BMinusA, minusSize);
setPrint("B-A", BMinusA, minusSize);
.
.
.
Instruction: Add the function setMinus() and test them inside the main() and see the output.