Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 数组洗牌不起作用_Java_Arrays_Algorithm_Random_Shuffle - Fatal编程技术网

Java 数组洗牌不起作用

Java 数组洗牌不起作用,java,arrays,algorithm,random,shuffle,Java,Arrays,Algorithm,Random,Shuffle,我正在尝试编写代码来洗牌数组而不使用集合 我的随机码 金额 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 Shuffl

我正在尝试编写代码来洗牌数组而不使用集合

我的随机码

金额

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);
            }
        }
    }
public void casesetup(){
对于(int i=0;i

我这里的问题是,它们没有被随机分配。有人知道为什么吗?

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

   for (int i=0; i > amounts.length; i++) {
难道不是吗

   for (int i=0; i < amounts.length; i++) {
for(int i=0;i
将值存储在列表中并使用 收藏(洗牌)


您自己手动滚动这个似乎不必要

除了for循环错误之外,您还应该更改

rgen.nextInt(amounts.length)


要获得均匀的随机分布。

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

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这将洗牌你的数组,每个排列的可能性都一样。这一点的论证是直截了当的。

试着做
i
而不是
是的,显然。除非他做这件事是作为一个练习/家庭作业,或者只是为了学习Java?而且,洗牌实际上是一个相当困难的问题m很容易出错。是的,使用
Collection.shuffle
并完成它。@Andrew:您可能想在问题中提到这一点。@Andrew:Random也是API的一部分。
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;
}