如何产生一个随机排列在Java中?排列、Java

2023-09-10 23:37:14 作者:情深与你

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

举例来说,假设我有一组数字1,2和3(N = 3)

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

现在,我该如何生成:

的上述套(随机选择的)的元素之一 在一个整体置换设置如上图所示 排序算法之冒泡排序 C C Java实现

在换句话说,如果我有n个元素的数组,我怎么洗牌他们随意?请协助。谢谢你。

解决方案

  java.util.Collections.shuffle(名单);
 

http://download.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#shuffle%28java.util.List%29

 名单,其中,整数GT;名单=新的ArrayList<整数GT;();
list.add(1);
list.add(2);
list.add(3);
java.util.Collections.shuffle(名单);
 

值得一提的是,有很多算法可以使用​​。下面是它是如何在Sun JDK实现的:

 公共静态无效的洗牌(名单<>列表,随机RND){
    INT大小=则为list.size();
    如果(大小和LT; SHUFFLE_THRESHOLD ||列表中的instanceof了RandomAccess){
        的for(int i =大小; I> 1;我 - )
            掉期(列表中,I-1,rnd.nextInt(I));
    } 其他 {
        对象ARR [] = list.toArray();

        //随机排列
        的for(int i =大小; I> 1;我 - )
            掉期(ARR,I-1,rnd.nextInt(I));

        //数组转储回列表
        的ListIterator它= list.listIterator();
        的for(int i = 0; I< arr.length;我++){
            it.next();
            it.set(ARR [I]);
        }
    }
}
 

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.

解决方案

java.util.Collections.shuffle(List);

http://download.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#shuffle%28java.util.List%29

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