PDA

View Full Version : How to randomly shuffle the elements within a QValueVector/QValueList?



luffy27
20th September 2007, 18:14
Let's say, I defined a QValueVector or QValueList with "int" type elements and also put some elements into the vector/list to fulfill the stucture. Then, I need a function that can randomly shuffle the elements' sequence which is already stored in my vector/list.

Is there some available methods provided by Qt3 to do this kind of work?
BTW: I have searched through the Qt's documents, but I failed to get such functions.

Thanks a lot.

marcel
20th September 2007, 19:04
See STL's next_permutation. But you could also create a simple algorithm of your own to generate a random permutation.

For example, if you have N elements in your initial vector, then allocate another int vector with N elements and for each index assign an random integer between 0..N-1, but make sure this is unique by testing with the previous elements. Next rearrange the elements in the first vector according to this order:


int x[] = {1, 2, 3, 4, 5};
...
int perm[] = {0, 2, 1, 4, 3 }

This would yield x = { 1, 3, 2, 5, 4 }

This is just to get you started. You could do without the second array.

wysota
20th September 2007, 19:37
The easiest way is to simply call std::shuffle() on the container.