Algortihms for the permutation of a string

I have looked at multiple sites for an algorithm on how to find the permutation of a string and I have not been able to find one. I know how to find the different permutations of a string on paper but I am not able to code it. If someone could show me how to write this type of program logically, that would be great.
I have looked at multiple sites for an algorithm on how to find the permutation of a string and I have not been able to find one.


Then your googling skills are absolutely horrid. You might want to try the search results for "C++ generating permutations" although the C++ isn't strictly necessary if all you're looking for is an algorithm.

Or you could let the library do the work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <algorithm>
#include <string>
#include <iostream>
 
std::string get_word()
{
    std::cout << "Enter the string: " ;

    std::string input ;
    std::cin >> input ;

    return input ;
}


int main()
{
    std::string to_permute = get_word() ;
    std::sort(to_permute.begin(), to_permute.end()) ;

    do {
        std::cout << to_permute << '\n';
    } while(std::next_permutation(to_permute.begin(), to_permute.end()));
}
Enter the string: cdaa
aacd
aadc
acad
acda
adac
adca
caad
cada
cdaa
daac
daca
dcaa
The way I believe std::next_permutation() does it is to try swapping the two rightmost characters. If that string is lexicographically "greater" than the original string, it returns that permutation. Otherwise, it swaps the next-to-last characters and repeats this check. If, after swapping all the characters, the string is still not lexicographically greater than the original, then we had a string that was the lexicographical "greatest" of the permutations, and we've just transformed it to the lexicographical "least" with all of our swaps.

So to get all the permutations, we can "sort" the characters of the string (treating it like an array) so we have the lexicographical "lowest" permutation, then repeat the process above to get each permutation from least to greatest.
I understand that there is a way to do it with complicated c++ syntax, but I was looking for a solution to write this program logically, or mathematically. I hope you understand what I mean.
Like using loops as well as arrays to switch all the characters and put them in all the different positions.
Thanks zhuge
Your explanation helped
Topic archived. No new replies allowed.