Wednesday 22 November 2017

C++ Program to Generate All Possible Combinations of a Given List of Numbers


Code:

#include     iostream

using namespace std;

// A function to print all combination of a given length from the given array.
void Combination(int a[], int reqLen, int start, int currLen, bool check[], int len) 
{
// Return if the currLen is more than the required length.
if(currLen > reqLen)
return;
// If currLen is equal to required length then print the sequence.
else if (currLen == reqLen) 
{
cout<<"\t";
for (int i = 0; i < len; i++) 
{
if (check[i] == true) 
{
cout<
}
}
cout<<"\n";
return;
}
// If start equals to len then return since no further element left.
if (start == len) 
{
return;
}
// For every index we have two options.
// First is, we select it, means put true in check[] and increment currLen and start.
check[start] = true;
Combination(a, reqLen, start + 1, currLen + 1, check, len);
// Second is, we don't select it, means put false in check[] and only start incremented.
check[start] = false;
Combination(a, reqLen, start + 1, currLen, check, len);
}

int main()
{
int i, n;
bool check[n];
cout<<"Enter the number of element array have: ";
cin>>n;

int arr[n];
cout<<"\n";

// Take the input of the array.
for(i = 0; i < n; i++)
{
cout<<"Enter "<
cin>>arr[i];
check[i] = false;
}

// For each length of sub-array, call the Combination().
for(i = 1; i <= n; i++)
{
cout<<"\nThe combination of  length "<
Combination(arr, i, 0, 0, check, n);
}
return 0;
}



Output:

Case 1:
Enter the number of element array have: 5

Enter 1 element: 1
Enter 2 element: 2
Enter 3 element: 3
Enter 4 element: 4
Enter 5 element: 5

The combination of  length 1 for the given array set:
        1
        2
        3
        4
        5

The combination of  length 2 for the given array set:
        1 2
        1 3
        1 4
        1 5
        2 3
        2 4
        2 5
        3 4
        3 5
        4 5

The combination of  length 3 for the given array set:
        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

The combination of  length 4 for the given array set:
        1 2 3 4
        1 2 3 5
        1 2 4 5
        1 3 4 5
        2 3 4 5

The combination of  length 5 for the given array set:
        1 2 3 4 5



More C++ Programs:













100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...