2014-10-11 87 views
1

我想要做的是洗牌二維數組的值。我有這個二維數組:如何在java中洗牌二維數組

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| 

我該怎麼辦呢?

+0

我只是做一個費雪耶茨具有解碼功能洗牌從1D指數要到2D指數。雖然可能是更好的方法。 – Obicere 2014-10-11 03:33:22

+0

我該怎麼做? – 2014-10-11 03:44:21

回答

1

看看Collections.shuffle的源代碼。它僅適用於1D集合,但它可以讓您瞭解一種方法:查看所有條目並使用隨機的其他條目交換每條條目。

如何用2D數組來做到這一點?假設它是一個大的1D陣列用於混洗。 假設每個行具有相同數量的列(否則它變得稍微更復雜的),則可以寫這個代碼,由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(); 
    } 
} 
0

要隨機播放一個二維陣列的n個元素的米陣列(索引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]] 

的靈感來自Wiki - 由於Obicere的評論