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();
}
}
난 그냥 피셔 - 예이츠는 2D 인덱스에 1D 지수에서 이동 디코딩 기능 셔플 않는 것 . 더 좋은 방법이있을 수 있습니다. – Obicere
어떻게 할 수 있습니까? –