How to generate a random permutation in Java?

2019-01-07 21:50发布

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.

3条回答
等我变得足够好
2楼-- · 2019-01-07 22:32
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]);
        }
    }
}
查看更多
再贱就再见
3楼-- · 2019-01-07 22:33

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.

查看更多
男人必须洒脱
4楼-- · 2019-01-07 22:35

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

查看更多
登录 后发表回答