Tuesday, May 6, 2014

Program for printing pemutations and combinations.

Description:
The below program prints permutation and combinations of a given string.

#include <iostream>
#include <string>

#include <stdlib.h>
#include <string.h>

using namespace std;
/*
 *  give all combinations of (abcd)
 *  {
 *   a + give all combinations of (bcd)
 *   b + give all combination of  (acd)
 *   c + give all combinations of (bad)
 *   d + give all combinations of (cba)
 *  }
 *
 */
void printPermutations(char output[], string input, int index, int searchindex, int r)
{

 
  if(1 == r)
  {
    for(int j = searchindex; j < input.length(); j++)
    {
       output[index] = input[j];
       cout << output << endl;
    }
    return;
  }

  for(int i = searchindex; i < input.length(); i++)
  {
    output[index] = input[searchindex];

     printPermutations(output, input, index + 1, searchindex + 1, r -1);

     input[searchindex] = input[i+1];
    input[i+1] = output[index];

  }
/*
 *                          abcdef
 *                         a  b c d
 *                      ab ac ad ae bc bd be cd ce de
 *      abc abd abe abf acd ace acf ade adf aef bcd bce bcf bde bdf bef cde cdf cef def
 *
 *
 *
 */
void printCombinations(char output[], string& input, int index, int searchindex,int r)
{

   //cout << index << "-" << searchindex << "-" << n << "-" << r << endl;

   if(1 == r)
   {
     for(int i = searchindex; i < input.length(); i++)
     {
       output[index] = input[i];
       cout << endl << output << " ";
     }
     return;
   }
   for(int j = searchindex; j+r <= input.length() ; j++)  // j < n
   {
     output[index] = input[j];
     printCombinations(output, input, index+1, j+1, r-1);
   }
}

int main(int argc, char** argv)
{
  int n,r;

  string input;

  cout << "Enter string:" << endl;

  cin >> input;

  cout << "How many you want to choose:" << endl;

  cin >> r;
  n = input.length();

  if(n < r)
  {
    cerr << "Invalid input" << endl;
    exit(1);
  }
  else if(n == r)
  {
    cout << "Possible combinations:" << endl << input << endl;
  }
  else
  {
   char* output = new char[r + 1];
   output[r] = '\0';

   cout << "Combinations:" << endl;

   printCombinations(output, input, 0, 0, r);

  }

   char* output = new char[n + 1];

   output[n] = '\0';
   cout << "Permutations:" << endl;
   printPermutations(output, input, 0, 0, r);

  exit(0);
}





Sample Ouput:

[root@localhost mytrials]# ./a.out
Enter string:
12345
How many you want to choose:
2
Combinations:

12
13
14
15
23
24
25
34
35
45 Permutations:
12
13
14
15
21
23
24
25
31
32
34
35
41
42
43
45
51
52
53
54