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

我想要做的是改变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| 

我希望它随机播放(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| 

我怎样才能做到这一点?

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

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

要将m个n个元素的数组(索引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的评论