TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

 Home » Tip Bank » Visual Basic » Windows
Language: C++
Apr 20, 2004

### WEBINAR:On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning

# 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

 Submit a Tip Browse "Visual Basic" Tips Browse All Tips
Thanks for your registration, follow us on our social networks to keep up-to-date