2014-10-11 2 views
1

내가 원하는 것은 2D 배열의 값을 섞는 것이다. 나는이 2 차원 배열이 있습니다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) shuffle을 원하는 :

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

난 그냥 피셔 - 예이츠는 2D 인덱스에 1D 지수에서 이동 디코딩 기능 셔플 않는 것 . 더 좋은 방법이있을 수 있습니다. – Obicere

+0

어떻게 할 수 있습니까? –

답변

1

Collections.shuffle의 소스 코드를 살펴보십시오. 1D 콜렉션에서만 작동하지만 접근 방식에 대한 아이디어를 제공합니다. 모든 항목을 검토하고 임의의 다른 항목으로 각 항목을 전환하십시오.

2D 배열을 사용하여이를 수행하는 방법은 무엇입니까? 셔플의 목적을 위해 하나의 큰 1D 배열 인 척하십시오.

/** 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 소자 m 배열의 2 차원 어레이를 셔플 (인덱스 : 각 행은 열 (그렇지 않으면, 약간 더 복잡하게된다)하면 Collections.shuffle 영감이 코드를 작성할 수와 동일한 수를 가지고 있다고 가정 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의 의견에 감사

관련 문제