A union of two sets (A
and B
) is the set of elements that are in A
, in B
, or in both A
and B
.
In C++, Set
has a property whereby all the elements it contains are unique.
A = {3,5,7 8,4,9}
B = {1,2,3,5,9,7,8,6}
AUB = { 3, 5, 7, 8, 4, 9, 1, 2, 6 }
#include <iostream>using namespace std;#define sizeOfA 6#define sizeOfB 8int findCommonElement(int setA[], int sizeOfSetA, int setB[], int sizeOfSetB){int commonElemnt =0;for(int i=0; i<sizeOfSetA; i++){for(int j=0; j<sizeOfSetB; j++){if(setA[i]==setB[j]){commonElemnt++;}}}}int *findUnion(int setA[], int sizeOfSetA, int setB[], int sizeOfSetB, int commonElement){int *unionArray;// Find the size of the new arrayint sizeOfUnionArray= sizeOfSetA + sizeOfSetB - commonElement;unionArray= new int[sizeOfUnionArray];int k=0; // Use this iterator to insert elements in the union arrayfor(int i=0; i<sizeOfSetA; i++){unionArray[k]=setA[i]; // Copy all the element of the arrayk++;}for(int i=0; i<sizeOfSetB; i++){bool isNotExit= true; // This variable is used to check element is exit or not in unionArrayfor(int j=0; j<sizeOfSetA; j++){if (setA[j]==setB[i])// This condition evaluates if element in both arrays is the same or not and change the isNotExit variable accordingly{isNotExit= false;}}if(isNotExit){unionArray[k]=setB[i];k++;}}return unionArray;}int main(){int * UnionArray;// Declare two arrays A and Bint A[sizeOfA] = {3,5,7,8,4,9};int B[sizeOfB] = {1,2,3,5,9,7,8,6};int commonElement=findCommonElement(A,sizeOfA, B,sizeOfB);// Get the number of the common elements of both arraysint sizeOfNewArray=sizeOfA+sizeOfB-commonElement;// Calculate the size of the new arrayUnionArray=findUnion(A,sizeOfA,B,sizeOfB, commonElement);//Print the array elementcout<<"{ ";for(int i= 0; i<=sizeOfNewArray; i++){if(i<sizeOfNewArray){cout<<UnionArray[i]<<", ";}else{cout<<UnionArray[i]<<" }";}}return 0;}
setA
and setB
.findCommonElement
function to find the common element of the two arrays.unionArray
or not.findUnion
function to find the union of the two arrays.unionArray
pointer to allocate memory dynamically, based on the sizeOfUnionArray
array.unionArray
.