Print all possible combination of the characters in a string.
#include <string.h>
#include <stdio.h>
#define RECURSION
#ifndef RECURSION
void combination(char *str, int num, int len)
{
char *tmp = new char[len+1];
int i = 0;
int x = 1;
int k = 0;
while(i < len){
x = 1 << i;
if(x&num){
tmp[k] = str[i];
k++;
}
i++;
}
tmp[k] = '\0';
printf("%s\n",tmp);
delete[] tmp;
}
#else
void str_comb2(char *pfx, int l1, char *str, int l2)
{
if(l2 == 0)
{
printf("%s\n", pfx);
}
else{
str_comb2(pfx, l1, str, l2 - 1);
pfx[l1] = str[l2 - 1];
pfx[l1 + 1] = '\0';
str_comb2(pfx, l1 + 1, str, l2 - 1);
}
}
void combination(char *pfx, char *str)
{
char pfx_0[20];
char str_0[20];
char tmp[20];
char pfx_1[20];
char str_1[20];
int len = strlen(str);
if(len == 1)
{
printf("%s%s\n", pfx, str);
}
else{
tmp[0] = str[0];
tmp[1] = '\0';
combination(pfx, tmp);
strcpy(pfx_0, pfx);
strcat(pfx_0, tmp);
strcpy(str_0, &str[1]);
combination(pfx_0, str_0);
strcpy(pfx_1, pfx);
strcpy(str_1, &str[1]);
combination(pfx_1, str_1);
}
}
#endif
int main(int argc, char *argv[])
{
char *str = "1234";
#ifndef RECURSION
int len = strlen(str);
int i;
int num = pow((double)2, (long)len);
for(i = 1; i < num; i++){
combination(str, i, len);
}
#else
char pfx[100] = "";
str_comb2(pfx, 0, str, 4);
#endif
return 1;
}
Output
1
2
21
3
31
32
321
4
41
42
421
43
431
432
4321