Answer to Question #239294 in C++ for raza

Question #239294

Suppose you have two arrays: a1[0…n-1] of size n and a2[0….m-1] of size m. Write a program that checks whether a2[] is a subset of a1[] or not. Both the arrays may or may not be sorted. It can be assumed that elements within an array are distinct. 


1
Expert's answer
2021-09-20T00:11:17-0400


#include <iostream>
 using namespace std;
//A function that checks if arr2 is a subset of arr1


bool is_subset(int a1[], int a2[], int m, int n)
{
    int x = 0;
    int y = 0;
    for (x = 0; x < n; x++) {
        for (y = 0; y< m; y++) {
            if (a2[x] == a1[y])
                break;
        }
 
        
        if (y == m)
            return 0;
    }
 
    return 1;
}
 
// Testing code
int main()
{
    int a1[] = {1,2,3,4,5,6,7,8,9 };
    int a2[] = { 4,5,6 };
 
    int size_a1 = sizeof(a1) / sizeof(a1[0]);
    int size_a2 = sizeof(a2) / sizeof(a2[0]);
 
    if (is_subset(a1, a2, size_a1, size_a2))
        cout<<"a2 array is  asubset of array a1 ";
    else
        cout<<"array a2 is not a subset of array a1";
 
   
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS