Print all possible combinations of r elements in a given array of size n in C++


In this problem, we are given an array of size n and a positive integer r. Our task is to print all possible combinations of the elements of the array of size r.

Let’s take an example to understand the problem −

Input: {5,6,7,8} ; r = 3
Output : {5,6,7}, {5,6,8}, {5,7,8}, {6,7,8}

To solve this problem an approach would be fixing elements and then recuring or looping over others to find all combinations. In this, we have to fix first n-r+1 elements only and loop or recur over the rest.

Example

#include<iostream>
using namespace std;
void printRElementCombination(int arr[], int combination[], int start, int
end, int index, int r){
   if (index == r){
      cout<<"{ ";
      for (int j = 0; j < r; j++)
         cout << combination[j] << " ";
         cout<<"}\t";
      return;
   }
   for (int i = start; i <= end && end - i + 1 >= r - index; i++){
      combination[index] = arr[i];
      printRElementCombination(arr, combination, i+1, end, index+1, r);
   }
}
int main(){
   int arr[] = {1, 2, 3, 4, 5};
   int r = 3;
   int n = 5;
   int combination[r];
   cout<<"The combination is : \n";
   printRElementCombination(arr, data, 0, n-1, 0, r);
}

Output

The combination is −

{ 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 }

Other methods to solve the same problem can be by checking the inclusion of current element in the combination and print all combinations of required size. The idea is the same, we will recure over the element and store the combination in combo array. But the fixing of the element is not done.

The below program will make the problem more understandable to you −

Example

 Live Demo

#include <iostream>
using namespace std;
void combinationUtil(int arr[], int n, int r, int index, int combo[], int i){
   if (index == r){
      cout<<"{";
      for (int j = 0; j < r; j++)
         cout << combo[j] << " ";
         cout<<"}\t";
         return;
   }
   if (i >= n)
      return;
   combo[index] = arr[i];
   combinationUtil(arr, n, r, index + 1, combo, i + 1);
   combinationUtil(arr, n, r, index, combo, i+1);
}
int main(){
   int arr[] = {1, 2, 3, 4, 5};
   int r = 3;
   int n = 5;
   int combo[r];
   cout<<"The combination is : \n";
   combinationUtil(arr, n, r, 0, combo, 0);
   return 0;
}

Output

The combination is −

{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 }

Updated on: 17-Jan-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements