Problem Solving: Difference between Sets (Using Functions)
Learn to calculate the difference between sets using the functions.
We'll cover the following
main.cpp
Sets.txt
void loadSet(const char Msg[], int S[ ], int &size, ifstream &rdr);void sort(int S[ ], int size);void setPrint(const char Msg[ ], int S[ ], int size);bool isPresent(int S[ ], int size, int t);/*Assume you have the implementation of the above 4 functions.*/void setMinus() // Add parameter list{// Add code here.}int main(){const int capacity = 500;int A[capacity] = { 0 }, B[capacity] = { 0 }, sizeA, sizeB;ifstream rdr("Sets.txt");cout << "Size of Set A = ";rdr >> sizeA; cout << sizeA<<"\n";cout << "Size of Set B = ";rdr >> sizeB; cout << sizeA<<"\n";loadSet("A",A, sizeA, rdr);loadSet("B",B, sizeB, rdr);//Displaying the two setssetPrint("A", A, sizeA);setPrint("B", B, sizeB);int BMinusA[500], AMinusB[500];int minusSize;// Write code for computing A-B// Printing A-B result// Write code for computing B-A// Printing B-Areturn 0;}
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 ofA1
that 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:
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.