How to Shuffle 2d array in java

What i want to do is shuffling the value of 2D array. I have this 2D array:

2.0|0.0|0.0|1.0|1.0|0.0|0.0|0.0|0.0|1.0|2.0|0.0|1.0|1.0|0.0|
0.0|0.0|0.0|0.0|0.0|0.0|0.0|0.0|1.0|0.0|1.0|1.0|0.0|0.0|0.0|
1.0|1.0|1.0|0.0|0.0|1.0|0.0|1.0|0.0|0.0|1.0|0.0|0.0|0.0|0.0|

and i want it shuffle to (eaxmple):

0.0|0.0|0.0|0.0|0.0|0.0|0.0|0.0|1.0|0.0|1.0|1.0|0.0|0.0|0.0|
1.0|1.0|1.0|0.0|0.0|1.0|0.0|1.0|0.0|0.0|1.0|0.0|0.0|0.0|0.0|
2.0|0.0|0.0|1.0|1.0|0.0|0.0|0.0|0.0|1.0|2.0|0.0|1.0|1.0|0.0|

how can i do that?

Upvotes: 2

Views: 5358

Answers (2)

bbusching
bbusching

Reputation: 79

To shuffle a 2d array a of m arrays of n elements (indices 0..n-1):

for h from m - 1 downto 0 do
  for i from n − 1 downto 1 do
    j ← random integer with 0 ≤ j ≤ i
    k ← random integer with 0 ≤ k ≤ h
    exchange a[k[j]] and a[h[i]]

inspired by Wiki - Thanks to Obicere's comment

Upvotes: 0

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31299

Have a look at the source code of Collections.shuffle. It works only on a 1D-collection but it gives you an idea of an approach: go over all entries and swap each with a random other entry.

How to do that with a 2D array? Pretend it's one big 1D array for the purpose of shuffling. Assuming that each row has the same number of columns (otherwise it becomes slightly more complex) you can write this code, inspired by Collections.shuffle:

/** Shuffles a 2D array with the same number of columns for each row. */
public static void shuffle(double[][] matrix, int columns, Random rnd) {
    int size = matrix.length * columns;
    for (int i = size; i > 1; i--)
        swap(matrix, columns, i - 1, rnd.nextInt(i));
}

/** 
 * Swaps two entries in a 2D array, where i and j are 1-dimensional indexes, looking at the 
 * array from left to right and top to bottom.
 */
public static void swap(double[][] matrix, int columns, int i, int j) {
    double tmp = matrix[i / columns][i % columns];
    matrix[i / columns][i % columns] = matrix[j / columns][j % columns];
    matrix[j / columns][j % columns] = tmp;
}

/** Just some test code. */
public static void main(String[] args) throws Exception {
    double[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } };
    shuffle(matrix, 3, new Random());
    for (int r = 0; r < matrix.length; r++) {
        for (int c = 0; c < matrix[r].length; c++) {
            System.out.print(matrix[r][c] + "\t");
        }
        System.out.println();
    }
}

Upvotes: 1

Related Questions