# Problem Description

Display different combinations of some letters forming a word. That is to say, to compute the combination of n characters.

For example:

If string entered is "sunil", the total no. of letters in the word is 5, i.e. s,u,n,i,l. And then displays
sunil
sunli
suinl
suiln
sulin
sulni

Another one, if string entered is "dipi", the total no. of letters forming the word is 3 i.e. d,i,p. And displays
dip
pid
idp
dpi
pdi
ipd

# Problem Analysis

1.  How to compute how many combinations there are?

count = n!

2.  loop + recursion

# Code

#include <stdio.h>
#include <stdlib.h>

void combine_all(char *ip, char *op, int len, int occupied, char **combination, int *curr);
char **combine(char *ip);

int main(int argc, char **argv)
{
char *ip;

int i;
char **result;

if(argc !=2)
{
printf("Improper usage. Use %s STRING", argv[0]);

getchar();
exit(1);
}

ip = argv[1];

result = combine(ip);

for (i=0; result[i] != NULL; i++)
{
printf("%s\n", result[i]);
free(result[i]);
}

free(result);

return 0;
}

char **combine(char* ip)
{
char *op,*temp;

int i,len;

int count;

char **combinations;
int curr;

for(i=0; ip[i]!='\0';i++);
len=i;

op = (char*)calloc(len,sizeof(char));
temp = (char*)calloc(len,sizeof(char));

for(i=0; i<len;i++)
temp[i]=ip[i];

printf("\n");

//count = n! factorial
count=1;
for(i=0; i<len; i++)
count*=(i+1);

combinations = (char**)calloc(count + 1,sizeof(char*));
curr = 0;
combinations[count] = NULL;

combine_all(temp,op,len,0,combinations,&curr);

free(op);
free(temp);

return combinations;
}

void combine_all(char *ip, char *op, int len, int occupied, char **combinations, int *curr)
{
int i,j,k;

char *temp;
if(len==0)
{
char *buffer = (char*) calloc(occupied, sizeof(char));
for(i=0;i<occupied;i++)
buffer[i] = op[i];

combinations[(*curr)++] = buffer;
}

temp = (char*)calloc(len-1,sizeof(char));
for(i=0;i<len;i++)
{
for(j=0,k=0;j<len-1;k++)
{
if(k==i)
continue;

temp[j]=ip[k];
j++;
}
op[occupied]=ip[i];

combine_all(temp,op,len-1,occupied+1, combinations, curr);
}

free(temp);
}