Reputation: 41
I'm making a game in Java and need to randomize the order of the board. Below is the code for what I am doing:
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();
}
Right now Java is telling me that "int[] cannot be converted to int[][]," but I am unsure why. Any help would be great.
Upvotes: 3
Views: 71
Reputation: 181
Your error is because you're trying to pass in a 2D array instead of a 1D array. For example, if you said RandomizeArray(board[0]);
, that would be a valid argument.
Or, you could change your RandomizeArray
method to:
public static int[] RandomizeArray(int[][] array) {
...
}
Note the additional []
in my argument. If you went this route you would need to rework your logic for randomizing.
Also, even if you were successfully calling your RandomizeArray()
method, you're rearranging your blank values, and then filling them with new values later on, thereby defeating your purpose to begin with.
Here is my approach to the problem.
The Collections class has a built shuffle method. Let's take advantage of that. Here is a full example.
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();
}
Upvotes: 2
Reputation: 361575
board
is a 2-dimensional int[][]
but RandomizeArray
expects a 1-dimensional int[]
. You'll need to change RandomizeArray
to work in two dimensions.
Upvotes: 2