如何在 Java 中生成随机排列? [英] How to generate a random permutation in Java?

查看:35
本文介绍了如何在 Java 中生成随机排列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

生成 n 个数字的随机排列的最佳方法是什么?

What is the best way to generate a random permutation of n numbers?

例如,假设我有一组数字 1、2 和 3 (n = 3)

For example, say I have a set of numbers 1, 2 and 3 (n = 3)

所有可能排列的集合:{123, 132, 213, 231, 312, 321}

Set of all possible permutations: {123, 132, 213, 231, 312, 321}

现在,我如何生成:

  • 上述集合的元素之一(随机选择)
  • 如上所示的整个排列集

换句话说,如果我有一个包含 n 个元素的数组,我该如何随机打乱它们?请协助.谢谢.

In other words, if I have an array of n elements, how do I shuffle them randomly? Please assist. Thanks.

推荐答案

java.util.Collections.shuffle(List);

javadocCollections.shuffle

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

值得注意的是,您可以使用很多算法.以下是它在 Sun JDK 中的实现方式:

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]);
        }
    }
}

这篇关于如何在 Java 中生成随机排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆