Hi
Would any one tell me how can I generate a random permutation of N numbers in c++?
Is there any algorithm in STL for this purpose?

4
Contributors
6
Replies
8
Views
8 Years
Discussion Span
Last Post by hamidvosugh

That was a great help, but what I am looking for is to output N permutations out of total M permutations Randomly. (N < M)

What sort of premutation? On what set?

What sort of premutation? On what set?

int array[] ={1,2,3,4};
The output of next_permutation() on the above array result in
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
.....
.....
2 4 3 1
...
...
What I like to be output is permutation of those numbers, but in different orders each time the function is called.
E.X
2 4 3 1
1 4 3 2
2 1 3 4
1 2 4 3
3 4 2 1
4 2 1 3
...
...
1 2 3 4

You can store all permutations in 2D vector. Then You need to create another vector with M! elements (indexes). Random_shuffle vector with indexes and you have order in which You should read data from 2D vector (with all permutations).
But since (N < M) this algorithm is little overkill, because no matter how big N would be, you always have to generate all permutations.

Edited by pecet: n/a

I have reached to the following idea which works quite well for me. Although it won't generate all the permutations in the given range.

int array[] = {1,2,3,4,5};
srand (time(0));
do{
}while(next_permutation(array, array +(rand()%5)));

Edited by hamidvosugh: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.