S
sanket
Hi all.
I wrote a program to print all permutations of the letters of a
string. Here are my two implementations
1.
include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char ** argv)
{
if(argc < 2) {cout << "Usage:\na.out <string>"<<
endl;abort();}
string s(argv[1]);
for(string::iterator i = s.begin(); i != s.end(); i++)
{
for(string::iterator j = s.begin(); j != s.end(); j++)
{
if(j == i) continue;
for(string::iterator k = s.begin(); k !=
s.end(); k++)
{
if(k == j || k == i) continue;
for(string::iterator p = s.begin(); p !
= s.end(); p++)
{
if(p == k||p == j||p == i)
continue;
cout << *i << *j << *k << *p
<< endl;
}
}
}
}
}
2.
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main(int argc, char ** argv)
{
if(argc < 2) {cout << "Usage:\na.out <string>"<<
endl;abort();}
string s(argv[1]);
sort(s.begin(), s.end());
cout << s << endl;
while(next_permutation(s.begin(), s.end())){cout << s <<
endl;}
return 0;
}
They seem to be working well, but I was wondering if there was a
better way to implement the same without using the STL function
next_permutation.
Thanks,
Sanket
I wrote a program to print all permutations of the letters of a
string. Here are my two implementations
1.
include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char ** argv)
{
if(argc < 2) {cout << "Usage:\na.out <string>"<<
endl;abort();}
string s(argv[1]);
for(string::iterator i = s.begin(); i != s.end(); i++)
{
for(string::iterator j = s.begin(); j != s.end(); j++)
{
if(j == i) continue;
for(string::iterator k = s.begin(); k !=
s.end(); k++)
{
if(k == j || k == i) continue;
for(string::iterator p = s.begin(); p !
= s.end(); p++)
{
if(p == k||p == j||p == i)
continue;
cout << *i << *j << *k << *p
<< endl;
}
}
}
}
}
2.
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main(int argc, char ** argv)
{
if(argc < 2) {cout << "Usage:\na.out <string>"<<
endl;abort();}
string s(argv[1]);
sort(s.begin(), s.end());
cout << s << endl;
while(next_permutation(s.begin(), s.end())){cout << s <<
endl;}
return 0;
}
They seem to be working well, but I was wondering if there was a
better way to implement the same without using the STL function
next_permutation.
Thanks,
Sanket