# Thread: Problem on repeated permutation

1. ## Problem on repeated permutation

I was trying to write a program that makes repeated
permutations of two given variables(a,b) in userdefined number
n(1<n<1000) of places.
for example
1)if user inputs 3,
then the output must be
aaa
aab
aba
abb
baa
bab
bba
bbb
2)if user inputs 4
then the output must be
aaaa
aaab
aaba
aabb
abaa
abab
abba
abbb
baaa
baab
baba
babb
bbaa
bbab
bbba
bbbb

My program works if only I know in advance how many places are there.
But my problem is to give a generic code that gives out output in any number of n.
Code:
```#include<stdio.h>
#include<conio.h>
int main(void)
{
int n;
char set[]="ab";
int i,j,k,l;
char str;
printf("How many places?\n");
scanf("%d",&n);
n=4;         //as this code will handle only 4 as input,needs improvement
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)  /*4 loops to handle 4 places,needs improvement*/
{
for(l=0;l<2;l++)
{
str=set[i];
str=set[j];
str=set[k];
str=set[l];
str='\0';
printf("%s\n",str);
}}}}
return 0;
}``` 2. There's a much better way to calculate permutations (which isn't exactly what you're doing, but w.e) than using a system of nested for loops.

You'll first need to set up a few variables:
Code:
```	int size_set = 2;
char *chrset = "ab";

int set_len = 4;
char res[set_len + 1];
char *tmp = res;

int n, pos, permc, perm_per_len, wordlen;```
Then, calculate how many permutations you'll actually need:
Code:
```	perm_per_len = 1;
for (n = 0; n < set_len; n++)
perm_per_len *= size_set;```
Finally, generate the actual permutations:
Code:
```	for (n = 0; n < perm_per_len; n++) {
permc = 1;
tmp = res;
for (wordlen = 0; wordlen < set_len; wordlen++) {
pos = (n / permc) % size_set;
*tmp++ = chrset[pos];
permc *= size_set;
}
printf("%s\n", res);
}```
Don't go and copy my code, but use it as an example. `char [res+1]` Popular pages Recent additions 