如何在java中随机播放2d数组

时间:2014-10-11 03:31:15

标签: java arrays double

我想做的是改变2D数组的值。我有这个2D数组:

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|

我想把它改成(例子):

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|

我该怎么做?

2 个答案:

答案 0 :(得分:1)

查看Collections.shuffle的源代码。它仅适用于1D集合,但它可以让您了解一种方法:遍历所有条目并使用随机的其他条目交换每个条目。

如何使用2D数组?假装它是一个大的一维阵列,用于改组。 假设每行具有相同的列数(否则它会变得稍微复杂一些),您可以编写此代码,灵感来自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();
    }
}

答案 1 :(得分:0)

将n个元素的m个数组(索引0..n-1)中的2d数组a洗牌:

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]]

Wiki的启发 - 感谢Obicere的评论