patterncppMinor
Another permutator
Viewed 0 times
anotherpermutatorstackoverflow
Problem
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:
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
#include
#include
std::vector permute(std::string s) {
std::vector retval;
if (s.length() > toPermute;
} else {
toPermute = argv[1];
}
std::vector 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;
}
}Solution
-
Technically, the code doesn't meet the requirements: displaying number of permutations is not requested. You may add an option to display it as well, but a simple invocation
-
Returns from
Just extract
-
Algorithm has exponential time complexity. It is OK, because of the nature of task. It also requires exponential amount of memory, and it is not OK. You are not asked to keep all permutations, you just need to display them. And there is a solution with constant memory requirements.
Technically, the code doesn't meet the requirements: displaying number of permutations is not requested. You may add an option to display it as well, but a simple invocation
permute string shall display only the permutations.-
Returns from
permute: a non-void function with no return at the very end may raise some eyebrows.Just extract
return retval; out of if/else construct:if (s.length() <= 1) {
retval.push_back(s);
} else {
...
}
return retval;-
Algorithm has exponential time complexity. It is OK, because of the nature of task. It also requires exponential amount of memory, and it is not OK. You are not asked to keep all permutations, you just need to display them. And there is a solution with constant memory requirements.
Code Snippets
if (s.length() <= 1) {
retval.push_back(s);
} else {
...
}
return retval;Context
StackExchange Code Review Q#58675, answer score: 4
Revisions (0)
No revisions yet.