How to Shuffle 2d array in java

吃可爱长大的小学妹 提交于 2019-12-08 03:28:16

问题


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?


回答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();
    }
}



回答2:


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



来源:https://stackoverflow.com/questions/26310775/how-to-shuffle-2d-array-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!