Sets Example in C++ Programming Code Intersect or Union of Set implementation Example Code
#include <iostream>
#include <cstdlib>
using namespace std;
const int SIZE = 10;
void init(int set[SIZE])
{
for (int i = 0; i < SIZE; i++)
{
set[i] = rand()%20 + 1;
}
}
void print(int set[SIZE])
{
for (int i = 0; i < SIZE; i++)
{
cout << set[i] << "\t" ;
}
cout << endl;
}
void intersect(int setA[SIZE], int setB[SIZE])
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
if (setA[i] == setB[j])
{
cout << setA[i] << "\t";
break;
}
}
}
cout << endl;
}
void unionSets(int setA[SIZE], int setB[SIZE])
{
int result[SIZE*2];
for (int i = 0; i < SIZE*2; i++)
{
result[i] = -1;
}
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE*2; j++)
{
if (result[j] == setA[i]) //if already added to set
{
break;
}
if (result[j] == -1)
{
result[j] = setA[i];
break;
}
}
}
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE*2; j++)
{
if (result[j] == setB[i]) //if already added to set
{
break;
}
if (result[j] == -1)
{
result[j] = setB[i];
break;
}
}
}
cout << "********************************"<<endl;
for (int i = 0; i < SIZE*2; i++)
{
if (result[i] == -1) break;
cout << result[i] << "\t" ;
}
cout << endl;
}
void sets()
{
srand(time(0));
int setA[SIZE];
int setB[SIZE];
init(setA);
init(setB);
print(setA);
cout << "----------------------------------------" << endl;
print(setB);
cout << "----------------------------------------" << endl;
cout << "----------------------------------------" << endl;
cout << "----------------------------------------" << endl;
//intersect(setA, setB);
unionSets(setA, setB);
}