Generate Permutations for a Given Set of Numbers

There may come a time when you need to generate the permutations of a given set of variables at hand, all of them belonging to the same type.

The C++ STL library?algorithm provides a rich set of functions that you can use without reinventing the wheel. And one of them is the next_permutation function.

Here is some sample code that uses next_permutation:

#include <algorithm>#include #include #include using namespace std;int main(void) { 	vector v;	v.push_back(1);	v.push_back(2);	v.push_back(3);  // Initialize all elements of a vector	while (next_permutation(v.begin(), v.end() ) ) {                     // Loop until all permutations are generated.		copy(v.begin(), v.end(), ostream_iterator(cout, ""));		cout << endl;	}	return 0;}                     --   Code To Generate Permutations of a 3 digit number '123' --

The above code generates the permutation for a 3 digit number 123. It generates all possible permutations of the given vector, except one, the one that happens to be the original pattern itself. The output of the above code, generating permutations for a set of numbers 1, 2, and 3 is given as follows:

Output: 132213231312321

This code has been compiled on the major development platforms, namely GCC 3.2.3 on Linux, GCC 3.2 on Solaris, and MS VC++ 6.0?it was found to be working fine.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: