29

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.

NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104
Shankar Raju
  • 4,356
  • 6
  • 33
  • 52

3 Answers3

38
java.util.Collections.shuffle(List);

javadoc link for Collections.shuffle

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
java.util.Collections.shuffle(list);

It's worth noting that there are lots of algorithms you can use. Here is how it is implemented in the Sun JDK:

public static void shuffle(List<?> list, Random rnd) {
    int size = list.size();
    if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
        for (int i=size; i>1; i--)
            swap(list, i-1, rnd.nextInt(i));
    } else {
        Object arr[] = list.toArray();

        // Shuffle array
        for (int i=size; i>1; i--)
            swap(arr, i-1, rnd.nextInt(i));

        // Dump array back into list
        ListIterator it = list.listIterator();
        for (int i=0; i<arr.length; i++) {
            it.next();
            it.set(arr[i]);
        }
    }
}
fabian
  • 80,457
  • 12
  • 86
  • 114
corsiKa
  • 81,495
  • 25
  • 153
  • 204
  • Thanks so much. But the api says it works in linear time. Is it possible for us to achieve this in less than O(n) complexity? – Shankar Raju Mar 31 '11 at 20:46
  • @Shankar: [Yes](http://stackoverflow.com/questions/3079633/random-permutation/3079642#3079642) – BlueRaja - Danny Pflughoeft Mar 31 '11 at 20:48
  • @Danny that's possible, but impractical. – corsiKa Mar 31 '11 at 20:49
  • 2
    @metdos can you elaborate? I believe it's the knuth shuffle, and he kind of wrote the book on algorithms. Literally. – corsiKa Mar 18 '12 at 15:57
  • Yes, you are right. I guess my problem is with the random generator. I created a list with length of 3, and I shuffled it 100000 times, and the results weren't satisfactory(is not close to uniform as much as I expect) – metdos Mar 19 '12 at 06:31
0

You can try RubyCollect4J

Ruby.Array.of(1, 2, 3).permutation().toA().sample();

It did exactly what you asked for. BTW, I am the author of this Java library.

wnameless
  • 491
  • 5
  • 2
-2

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

bvk256
  • 1,837
  • 3
  • 20
  • 38