生成随机非重复数字2d数组 - 所有数字相同

时间:2014-10-08 13:09:29

标签: java arrays numbers generated

这个问题适用于Java。我一直在尝试创建一个大小为N的Block [] [],其中数字0 - 9是随机放置的。我创建了一个数组,然后将其洗牌以防止数字被重复。当我遍历数组并将数字分配给二维数组时,我继续发现二维数组中的所有数字都是相同的。该块继续出现:

222

222

222

我非常感谢你的帮助!

public class Board {

int N = 3; 
static int [][] copy; 

//construct a board from an N-by-N array of blocks 
//(where blocks[i][j] = block in row i, column j) 
public Board(int[][] blocks){
    blocks =  new int[N][N]; //creates array of size N
    //generates random numbers 0 inclusive to # exclusive 
    List<Integer> randomList = new ArrayList<>(); 
    for (int i = 0; i < blocks.length; i++){
        randomList.add(i); 
    }
    int randomNum = 0; 
    for (int i = 0; i < blocks.length; i++){
        randomNum = randomList.get(i); 
    }
    Collections.shuffle(randomList);
    for (int i = 0; i < blocks.length; i++){
        for (int j = 0; j < blocks[i].length; j++){
            blocks[i][j] = randomNum; 
        }
    }
    copy = blocks.clone(); 
}

4 个答案:

答案 0 :(得分:0)

问题是您是将randomNum的值分配给所有单元格。此变量在第二个for - 循环之前定义,并保留在该循环终止的最高值(在您的示例中为值2)。

您可能希望从randomList添加一个值,然后在i索引发生变化时重新调整它。

答案 1 :(得分:0)

您选择随机数的代码根本没有随机性:

int randomNum = 0; 
for (int i = 0; i < blocks.length; i++){
    randomNum = randomList.get(i); 
}

之后您会随机播放randomList,但之后不会使用随机播放列表。

答案 2 :(得分:0)

   int counter = 0;
   Collections.shuffle(randomList);
    for (int i = 0; i < blocks.length; i++){
        for (int j = 0; j < blocks[i].length; j++){
            blocks[i][j] = randomList.get(counter);
            counter++; 
        }
    }

你应该创建一个计数器,它将循环遍历原始arraylist的每个元素并分配给多维arraylist

同样改变:

 for (int i = 0; i < 10; i++){
        randomList.add(i); 
    }

你说你想要0-9,上面的循环会给你0-9。你拥有的循环只会给你0-2。

答案 3 :(得分:0)

您需要使用您正在设置的位置的随机列表中的值。除此之外,如果要插入0-9值,则需要修改随机列表创建:

public Board(int[][] blocks){
    blocks =  new int[N][N]; //creates array of size N
    //generates random numbers 0 inclusive to # exclusive 
    List<Integer> randomList = new ArrayList<>();

    for (int i = 0; i < 10; i++){
        randomList.add(i); 
    }

    Collections.shuffle(randomList);
    for (int i = 0; i < blocks.length; i++){
        for (int j = 0; j < blocks[i].length; j++){
            blocks[i][j] = randomList.get(j); 
        }
        // Shuffle the list again to get different values for the next line
        Collections.shuffle(randomList);
    }
    copy = blocks.clone(); 
}