Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Advanced
Apr 19, 2004

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 <iterator>
#include <vector>
#include <iostream>

using namespace std;

int main(void) { 
	vector<int> 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<int>(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: 

132
213
231
312
321
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.

Karthik Kumar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap