I have set of values eg: {1,2} , {1,2,3} ... etc.
How to find all permutation including duplicates values for length N.
Input: value = {1,2} ; N =3
output: 111,112,121,122,211,212,221,222
N>no. of values
so if we take {1,2,3} then N > 3
Not able to figure out proper algorithm for this.
I thought of implementing backtracking but I don't think any modification on it can solve this problem, Please correct me if I'm wrong.
I found a C++ solution to this. All permutations of length k from n characters with repetition in CPP
Tried to convert it to C:
void print_str(char str[], char *prefix, int n, int length)
{
if (length == 1)
{
for (int j = 0; j < n; j++)
printf("%s%c\n",prefix,str[j]);
}
else
{
for (int i = 0; i < n; i++)
{
char a = str[i];
char *b = &a;
print_str(str, b, n, length - 1);
}
}
}
int main()
{
int length = 3;
char *ab=malloc(sizeof(char)*length);
char str[] = "12";
int n = 2;
print_str(str, ab, n, length);
return 0;
}
But still not getting proper output.
Output: 11 12 21 22 11 12 21 22
Note: Other Input values {A,B} {+,-} etc.
Why will backtracking not work? Here's an easy Python implementation:
and this run with