-6

I'm looking for print only Unique permutation. Function that should take one string as input and print out the unique permutations (without repeating) of that string in lexicographic (alphabetical) order.

this is what i have so far but when I run it gave me an error. I think my parameters in the printPermutations doesn't match the main function but I can't change the main function because it was given to test the code.

void printPermutations(string word, int currentIndex, int wordSize){

if(currentIndex == wordSize){
    cout << word << endl;
    return;
}
else{
    for (int j = currentIndex; j = wordSize; j++){
        swap(word[currentIndex], word[j]);
        printPermutations(word, currentIndex +1, wordSize);
        swap(word[currentIndex], word[j]);
    }
}

}

int main(int argc, char* argv[]){
string word = "abcd";
printPermutations(argv[1]);
return 0;
}
  • If you are looking for how to print all the permutations, this takes 3 lines of C++ code to accomplish this. – PaulMcKenzie Feb 04 '15 at 02:43
  • I'm looking for print only Unique permutation. Function that should take one string as input and print out the unique permutations (without repeating) of that string in lexicographic (alphabetical) order. – Dang Nguyen Feb 04 '15 at 02:46
  • @Dang http://stackoverflow.com/questions/1995328/are-there-any-better-methods-to-do-permutation-of-string – James Moore Feb 04 '15 at 02:50
  • sorry guys this is my first time on here. – Dang Nguyen Feb 04 '15 at 02:50

1 Answers1

0

As has been rather poignantly identified what you are looking for is next_permutation You could do something like this:

void printPermutations(const string& word){
    sort(word.begin(), word.end());

    cout << "1. " << word << endl;

    for(int i = 2; next_permutation(word.begin(), word.end()); ++i){
        cout << i << ". " << word << endl;
    }
}
Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288