summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKohei Yoshida <kyoshida@novell.com>2010-08-23 21:00:30 -0400
committerKohei Yoshida <kyoshida@novell.com>2010-08-23 21:00:30 -0400
commit5cb64c4bf11b233958a0f44edca39a1cab3a030f (patch)
treeffe1c5ae906d354d3ea3adf2bfacec2e63e7311e
parenta210e6b9ce2a450e754929c13d643d7a86200285 (diff)
Slightly shorter solution.
-rw-r--r--permute.cpp32
1 files changed, 8 insertions, 24 deletions
diff --git a/permute.cpp b/permute.cpp
index 741455f..0829550 100644
--- a/permute.cpp
+++ b/permute.cpp
@@ -5,17 +5,10 @@
#include <string>
#include <vector>
#include <algorithm>
+#include <iterator>
using namespace std;
-struct string_printer : unary_function<void, string>
-{
- void operator()(const string& s)
- {
- cout << s << endl;
- }
-};
-
void do_permute(const string& pool, string& perm, vector<string>& perms)
{
if (pool.empty())
@@ -28,6 +21,7 @@ void do_permute(const string& pool, string& perm, vector<string>& perms)
for (size_t i = 0; i < n; ++i)
{
string tmp;
+ tmp.reserve(n-1);
for (size_t j = 0; j < n; ++j)
{
if (i == j)
@@ -40,25 +34,15 @@ void do_permute(const string& pool, string& perm, vector<string>& perms)
}
}
-void permute(const char* s, size_t n)
+void permute(const string& pool)
{
vector<string> perms;
- for (size_t i = 0; i < n; ++i)
- {
- string remain, perm;
- for (size_t j = 0; j < n; ++j)
- {
- if (i == j)
- perm.push_back(s[j]);
- else
- remain.push_back(s[j]);
- }
- do_permute(remain, perm, perms);
- perm.resize(perm.size()-1);
- }
+ string perm;
+ perm.reserve(pool.size());
+ do_permute(pool, perm, perms);
cout << "number of permutations: " << perms.size() << endl;
- for_each(perms.begin(), perms.end(), string_printer());
+ copy(perms.begin(), perms.end(), ostream_iterator<string>(cout, "\n"));
}
int main(int argc, char** argv)
@@ -68,7 +52,7 @@ int main(int argc, char** argv)
size_t n = strlen(argv[1]);
cout << "input string: " << argv[1] << " (len = " << n << ")" << endl;
- permute(argv[1], n);
+ permute(string(argv[1],n));
return EXIT_SUCCESS;
}