Write an algorithm that prints out all the subsets of 3 elements of a set of n elements. The elements of the set are stored in a list that is the input to the algorithm, (you may assume all elements in the list are distinct. The list can be an array). Algorithm: Print_3_Element_Subsets Input: List S of n distinct elements. Output: Print out all 3-element subsets of S. void Print_3_Element_Subsets (int n, const element_type S[])

Respuesta :

void Print_3_Element_Subsets(int n,const element_type S[])

{

if(n<3) // condition to check if list have less than 3 elements

{

print("No subset found");

}

for(int i =0; i < n ; i++)

{

for(int j =i+1; j < n ; j++)

{

for(int k =j+1; k < n ; k++)

{

print(S[i],S[j],S[k]);

}

}

}

}

C++ Implementation;

#include<cstdlib>

#include<time.h>

using namespace std;

int S1[5]= {1,2,3,4,5};

int n1 = 5;

int S2[2]={1,2};

int n2 = 2;

void Print_3_Element_Subsets(int n,const int S[])

{

if(n<3) // condition to check if list have less than 3 elements

{

printf("No subset found\n");

}

printf("3 Subsets are\n");

for(int i =0; i < n ; i++)

{

for(int j =i+1; j < n ; j++)

{

for(int k =j+1; k < n ; k++)

{

cout<<S[i]<<" "<<S[j]<<" "<<S[k]<<endl;

}

}

}

}

int main()

{

cout<<"Case 1"<<endl;

Print_3_Element_Subsets(n1,S1);

cout<<endl<<"Case 2"<<endl;

Print_3_Element_Subsets(n2,S2);

}

OUTPUT

Case 1

3 Subsets are

1 2 3

1 2 4

1 2 5

1 3 4

1 3 5

1 4 5

2 3 4

2 3 5

2 4 5

3 4 5

Case 2

No subset found

3 Subsets are

--------------------------------

Process exited after 0.0137 seconds with return value 0

Press any key to continue . . .

ACCESS MORE
EDU ACCESS