Java 如何将int[]随机化?
我正在用Java制作一个游戏,需要随机排列棋盘的顺序。下面是我正在做的代码:Java 如何将int[]随机化?,java,Java,我正在用Java制作一个游戏,需要随机排列棋盘的顺序。下面是我正在做的代码: public static int[] RandomizeArray(int[] array){ Random rgen = new Random(); for (int i=0; i<array.length; i++) { int randomPosition = rgen.nextInt(array.length); int temp = arra
public static int[] RandomizeArray(int[] array){
Random rgen = new Random();
for (int i=0; i<array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
int temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
return array;
}
public void startNewGame(){
numTries = 0;
won = false;
board = new int[4][4];
RandomizeArray(board);
for (int row = 0; row < 4; row++){
for (int col = 0; col < 4; col++){
board[row][col] = (row+1) + (4 * col);
}
}
repaint();
}
publicstaticint[]randomizarray(int[]array){
Random rgen=新的Random();
对于(int i=0;i电路板
是二维的int[][
但是randomizarray
需要一维的int[]
。您需要更改randomizerray
以在二维中工作。您的错误是因为您试图传入二维数组而不是一维数组。例如,如果您说randomizerray(board[0]);
,这将是一个有效的参数
或者,您可以将randomizarray
方法更改为:
public static int[] RandomizeArray(int[][] array) {
...
}
请注意我的论点中附加的[]
。如果你走这条路,你将需要修改你的随机逻辑
此外,即使您成功地调用了randomizarray()
方法,您也在重新排列空白值,然后用新值填充它们,从而破坏了您的初衷
以下是我解决问题的方法。
Collections类有一个内置的shuffle方法。让我们利用它。下面是一个完整的示例
public void startNewGame() {
int boardSize = 4;
numTries = 0;
won = false;
board = new int[boardSize][boardSize];
ArrayList<Integer> temp = new ArrayList();
for (int row = 0; row < boardSize; row++) {
for (int col = 0; col < boardSize; col++) {
temp.add((row + 1) + (boardSize * col));
}
}
Collections.shuffle(temp);
for (int row = 0; row < boardSize; row++) {
for (int col = 0; col < boardSize; col++) {
board[row][col] = temp.get(row * boardSize + col);
}
}
repaint();
}
public void startNewGame(){
int boardSize=4;
numTries=0;
赢=假;
board=新int[boardSize][boardSize];
ArrayList temp=新的ArrayList();
用于(int row=0;row
对于startNewGame
中的循环,您需要类似嵌套的东西。或者,您可能需要在板的每一行上调用randomizarray
,而不是对整个数组进行随机化。您的代码使用的是2D数组,而不是数组列表
。您的ter应该更精确米诺学。