3

我正在尝试编写代码以在不使用集合的情况下对数组进行洗牌。

我的洗牌码

金额

private double amounts[] = { 0, 0.01, 1000000, 25, 250000, 75, 50, 1000,
            200, 100, 400000, 750, 5000, 750000, 500, 100000, 300, 75000, 800,
            20, 300000, 10, 50, 750, 25, 5, 1 };

public void Shuffle(){

        Random rgen = new Random();
        for (int i=0; i > amounts.length; i++) {
            int randomPosition = rgen.nextInt(amounts.length);
            double temp = amounts[i];
            amounts[i] = amounts[randomPosition];
            amounts[randomPosition] = temp;
    }
    }

启动它的代码

public void casesSetup() {  

        for (int i = 0; i < briefcase.length; i++) {

            if (i == 0) {

            } else {
                briefcase[i] = new Briefcase();
                double value = amounts[i];
                briefcase[i].setAmount(value);
                briefcase[i].setFace(i);
            }
        }
    }

我的问题是他们没有被随机化,有人知道为什么吗?

4

4 回答 4

5

第一个片段中的 for 循环似乎是错误的

   for (int i=0; i > amounts.length; i++) {

不应该

   for (int i=0; i < amounts.length; i++) {
于 2011-09-09T14:02:21.703 回答
3

将值存储在列表中并使用 Collections.shuffle http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List )

自己手动滚动似乎没有必要

于 2011-09-09T14:03:03.727 回答
1

我的建议是反向开始洗牌:

Random rgen = new Random();
for (int i = amounts.length - 1; i > 0; --i) {
   int randomPosition = rgen.nextInt(i + 1);
   double temp = amounts[i];
   amounts[i] = amounts[randomPosition];
   amounts[randomPosition] = temp;
}

假设 Random.nextInt(N) 的分布在 0..N-1 上是均匀的,这将对您的数组进行洗牌,每个排列的可能性相同。对此的论证是直截了当的。

于 2011-09-09T16:27:14.740 回答
0

除了你的 for 循环是错误的,你应该改变

rgen.nextInt(amounts.length)

rgen.nextInt(amounts.length - i) + i

得到均匀的随机分布。

于 2011-09-09T15:39:23.310 回答