# Shuffling a 2D array

• September 3rd, 2011, 07:25 AM
Buzzins
Shuffling a 2D array
Code :

public class Puzzle {
public static String[][] grid = new String[4][4];

public static void setupGame(){
int count = 1;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
grid[i][j] = Integer.toString(count++);
}
grid[3][3] = "?";

}
}

My array is populated by numbers from 1-15 with a "?" as the last element. I was wondering what would be the easiest way to shuffle this so that each time a button is pressed it shuffles each position?
• September 3rd, 2011, 07:44 AM
Norm
Re: Shuffling a 2D array
Do you want all 16 items in the array to be shuffled as if they were in a single array, or do you want what is in row to be shuffled only within that row or column?
If all elements as in a single array, copy them to a single dim array and use the Collections shuffle method and then copy them back to the 2 dim.
• September 3rd, 2011, 07:51 AM
Buzzins
Re: Shuffling a 2D array
shuffled as in a single array, I'm not too sure how to get the vaulues from the 2dim array to the single however?
• September 3rd, 2011, 07:58 AM
Norm
Re: Shuffling a 2D array
Use a nested loop for the 2 dim and have a separate index for the one dim

Why are you using a 2 dim array? With a little arithmetic you can use a one dim array almost as easily as a 2 dim array.
• September 3rd, 2011, 08:02 AM
Buzzins
Re: Shuffling a 2D array
I was using a 2dim as it sets up a 4x4 grid to find the values for the game
• September 3rd, 2011, 08:07 AM
Norm
Re: Shuffling a 2D array
You can simulate a 2 dim array with a one dim array by using an equation to compute the index given the row and column.
Something like: ix = row*nbrcols + col (off the top of my head, I'm sure it needs some adjustment)
• January 16th, 2012, 12:47 PM
roscowgo
Re: Shuffling a 2D array
You could do what I'm doing in that particular case, create an arraylist, pass the 2d array into it via for loops, then use Collections.shuffle();