Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Shuffling a 2D array

1. ## Shuffling a 2D array

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?

2. ## 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.

3. ## 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?

4. ## 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.

5. ## Re: Shuffling a 2D array

I was using a 2dim as it sets up a 4x4 grid to find the values for the game

6. ## 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)

7. ## 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();