Here is a standard function to print the permutations of characters of a string:
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf(\
I would do it the following way: First, I generate "groups" of characters (i.e. AABBBC
yields two groups: (AA) and (BBB) and (C)
.
First, we iterate over all distributions of AA
onto the n
characters. For each distribution found, we iterate over all distributions of BBB
onto the n-2
remaining characters (not occupied by an A
). For each of these distributions involving A
s and B
s, we iterate over all distributions of C
onto the remaining free character positions.
void permute(string set, string prefix = ""){
if(set.length() == 1){
cout<<"\n"<<prefix<<set;
}
else{
for(int i=0; i<set.length(); i++){
string new_prefix = prefix;
new_prefix.append(&set[i], 1);
string new_set = set;
new_set.erase(i, 1);
permute(new_set, new_prefix);
}
}
}
And simply use it as permute("word");
It would quite simple if you just think it as a problem where you need to store all the permutations for some future use.
SO you'll have an array of permuted strings.
Now think of a new problem, which is also an standard one where you need to remove the duplicates from array.
I hope that helps.
You can use std::set
to ensure uniqueness of the results. That is if it is C++ (because you tagged it as such).
Otherwise - go through the list of the results manually and remove duplicates.
You'll have to save the results and post-process them of course, not print immediately as you do now.