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

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

问题描述

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

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

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

现在,我该如何生成:

  • 的上述套(随机选择的)
  • 的元素之一
  • 在一个整体置换设置如上图所示

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

解决方案

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

<一个href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#shuffle%28java.util.List%29">http://download.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#shuffle%28java.util.List%29

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

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

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

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

        //数组转储回列表
        的ListIterator它= list.listIterator();
        的for(int i = 0; I&LT; 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]);
        }
    }
}

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

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