What is the best way to generate a random permutation of n numbers?
For example, say I have a set of numbers 1, 2 and 3 (n = 3)
Set of all possible permutations: {123, 132, 213, 231, 312, 321}
Now, how do I generate:
- one of the elements of the above sets (randomly chosen)
- a whole permutation set as shown above
In other words, if I have an array of n elements, how do I shuffle them randomly? Please assist. Thanks.
javadoc link for
Collections.shuffle
It's worth noting that there are lots of algorithms you can use. Here is how it is implemented in the Sun JDK:
You can try RubyCollect4J
It did exactly what you asked for. BTW, I am the author of this Java library.
Do you ask about a permutation generator? Because your permutation set is missing two numbers. Anyway you may look at the permutations generator on http://www.merriampark.com/perm.htm