1

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?

  • I'd just do a Fisher-Yates shuffle with a decoding function to go from the 1D index to a 2D index. Might be better ways out there though. – Obicere Oct 11 '14 at 03:33

2 Answers2

1

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();
    }
}
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
0

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

bbusching
  • 79
  • 1