This is a solution to this problem. The problem statement:
write a program to display all possible permutations of a given input string--if the string contains duplicate characters, you may have multiple repeated results. Input should be of the form
permute string
and output should be a word per line.
This is my code:
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> permute(std::string s) {
std::vector<std::string> retval;
if (s.length() <= 1) {
retval.push_back(s);
return retval;
} else {
for (size_t i = 0; i < s.length(); ++i) {
std::rotate(s.begin(), s.begin() + 1, s.end());
for (std::string permutation : permute(s.substr(1, std::string::npos))) {
retval.push_back(s.substr(0,1).append(permutation));
}
}
return retval;
}
}
int main(int argc, char **argv) {
std::string toPermute;
if (argc < 2) {
std::cout << "Please enter a word to permute:" << std::endl;
std::cin >> toPermute;
} else {
toPermute = argv[1];
}
std::vector<std::string> result = permute(toPermute);
std::cout << "Number of permutations: " << result.size() << std::endl;
std::cout << std::string(24, '=') << std::endl;
for (std::string permutation : result) {
std::cout << permutation << std::endl;
}
}
std::next_permutation()
The number of permutations of a string isfactorial(string.size())
\$\endgroup\$std::next_permutation
is in one of the answers already. I only included the number of permutations to be able to verify the algorithm generated the right number (by computing the factorial) so replacing that with the factorial function would sort of defeat the purpose. @LokiAstari \$\endgroup\$