C++
Write a program that takes two integer arrays of different sizes
from the user (this means that the user can tell the program the
size of each array), and then computes the intersection and union
of those arrays.
Note: the arrays can be of different lengths and the
intersection/union should have unique elements in sorted order. Use
pointer notation of arrays for this question. Eg: *(arr+1) [10]
#include <iostream>
using namespace std;
// helper function that returns true if given element found in given array
bool found(int *array, int size, int find)
{
// search find in array
for (int i = 0; i < size; i++)
if (*(array + i) == find)
return true;
return false;
}
int main()
{
// Write a program that takes two integer arrays of different sizes from the user
// (this means that the user can tell the program the size of each array),
int size1, size2;
// get size of first array
cout << "Enter size of first array: ";
cin >> size1;
int array1[size1];
// input first array
cout << "Enter array: ";
for (int i = 0; i < size1; i++)
cin >> *(array1 + i);
cout << "Enter size of second array: ";
cin >> size2;
int array2[size2];
// input second array
cout << "Enter array: ";
for (int i = 0; i < size2; i++)
cin >> *(array2 + i);
int union_size = 0, intersection_size = 0;
// computes the intersection
int intersection_array[size1 + size2];
// loop over first array
for (int i = 0; i < size1; i++)
{
// if found in second array too
if (found(array2, size2, *(array1 + i)))
{
// insert to union
*(intersection_array + intersection_size) = *(array1 + i);
intersection_size++;
}
}
// computes the union
int union_array[size1 + size2];
// loop over first array
for (int i = 0; i < size1; i++)
{
// insert to union
*(union_array + union_size) = *(array1 + i);
union_size++;
}
// loop over second array
for (int i = 0; i < size2; i++)
{
// if not found in first array
if (!found(array1, size1, *(array2 + i)))
{
// insert to union
*(union_array + union_size) = *(array2 + i);
union_size++;
}
}
// print intersection
cout << "\nIntersection: ";
for (int i = 0; i < intersection_size; i++)
cout << intersection_array[i] << " ";
// print union
cout << "\nUnion: ";
for (int i = 0; i < union_size; i++)
cout << union_array[i] << " ";
}
.
Output:
.
Get Answers For Free
Most questions answered within 1 hours.