All possible combinations of a string
1. Finds all possible cominations of a given string. The total number of combinations with recurrences is the factorial of the string length.
2. Have given the word 'post' as an example since if I included a cin >> word; then a user may unconscientiously enter a long word which will take toooo long to end. To change to another word change the string str.
3. A 9 letter word like 'aeroplane' can take around 40 seconds on a 1GHz machine. A 10 letter word will take 9 x 40 s - thats 6 mins! So watch out for the string length.
4. This may time according to the length of the string str
1. Finds all possible cominations of a given string. The total number of combinations with recurrences is the factorial of the string length.
2. Have given the word 'post' as an example since if I included a cin >> word; then a user may unconscientiously enter a long word which will take toooo long to end. To change to another word change the string str.
3. A 9 letter word like 'aeroplane' can take around 40 seconds on a 1GHz machine. A 10 letter word will take 9 x 40 s - thats 6 mins! So watch out for the string length.
4. This may time according to the length of the string str
Code: CPP
// Combination
#include<iostream.h>
#include<string.h>
#include<conio.h>
unsigned long fact(unsigned long); // finds factorial of a number
void swap(int[],int,int);
void display(int[],char[]);
void Add(int[],int);
void main()
{
// clrscr(); // Remove the first comment tag if running in TC++ or BC++ DOS mode
int j,k,n;
unsigned long i;
char str[]="post"; // small word
n=strlen(str);
int*key=new int[n+1];
key[0]=n; // key[0] contains the total no: of letters
for (i=1;i<=key[0];i++)
key[i]=i;
display(key,str);
swap(key,key[0],key[0]-1);
display(key,str);
for (i=3;i<=fact(key[0]);i+=2)
{
for (j=key[0]-1;j>=0;j--)
{
if ((i-1)%fact(j)==0)
{
Add(key,key[0]-j);
for (k=1;k<=key[0]-j-1;k++)
if (key[k]==key[key[0]-j])
{Add(key,key[0]-j);k=0;}
}
}
display(key,str);
swap(key,key[0],key[0]-1);
display(key,str);
}
cout << "\nTotal no: of combinations = " << key[0] << "! = " << i-1;
getch();
}
unsigned long fact(unsigned long f)
{
return f==0?1:f*fact(f-1);
}
void swap(int k[],int a,int b)
{
int t=k[a];k[a]=k[b];k[b]=t;
}
void display(int k[],char s[])
{
for(int i=1;i<=k[0];i++)
cout << s[k[i]-1];
cout << '\t';
}
void Add(int k[],int i)
{
k[i]++;
if (k[i]==k[0]+1)
k[i]=1;
}

