How to generate a random permutation in Java?

后端 未结 3 1213
小鲜肉
小鲜肉 2020-11-30 08:59

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 permutati

3条回答
  •  隐瞒了意图╮
    2020-11-30 09:24

    java.util.Collections.shuffle(List);
    

    javadoc link for Collections.shuffle

    List list = new ArrayList();
    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

提交回复
热议问题