How to find a union of two arrays in C++
Overview
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.
Example
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 }
Code
#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;}
Explanation
- Lines 3 to 4: We define the size of the two arrays,
setAandsetB. - Line 5: We implement the
findCommonElementfunction to find the common element of the two arrays. - Line 34 to 37: We already check elment is present in the
unionArrayor not. - Line 19: We implement the
findUnionfunction to find the union of the two arrays. - Line 52: We declare the
unionArraypointer to allocate memory dynamically, based on thesizeOfUnionArrayarray. - Lines 60 to 71: We print the data of the
unionArray.