第一种是随机索引交换位置 后面两种是转换为一维数组打乱顺序后再转回来 第三种是二维数组中一维数组长度不一致的情况
指定随机种子使每次运行随机结果一致
import java.util.*; public class Main { public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // 输出打乱后的二维数组 System.out.println("原始二维数组:"); for (int[] row : matrix) { System.out.println(Arrays.toString(row)); } System.out.println(); for (int[] row : shuffle2DArray(matrix)) { System.out.println(Arrays.toString(row)); } System.out.println(); for (int[] row : shuffle2DArray2(matrix)) { System.out.println(Arrays.toString(row)); } System.out.println(); for (int[] row : shuffle2DArray3(matrix)) { System.out.println(Arrays.toString(row)); } } public static int[][] shuffle2DArray(int[][] matrix) { List<Integer> flatList = new ArrayList<>(); // 将二维数组扁平化为一维列表 for (int[] row : matrix) { for (int element : row) { flatList.add(element); } } // 创建随机数生成器 Random r = new Random(42); // 打乱一维列表 Collections.shuffle(flatList, r); // 重新构建二维数组 int rows = matrix.length; int cols = matrix[0].length; int[][] shuffledMatrix = new int[rows][cols]; int index = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { shuffledMatrix[i][j] = flatList.get(index++); } } return shuffledMatrix; } public static int[][] shuffle2DArray2(int[][] matrix){ Random r = new Random(42); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { int randomRow = r.nextInt(matrix.length); int randomCol = r.nextInt(matrix[0].length); int temp = matrix[i][j]; matrix[i][j] = matrix[randomRow][randomCol]; matrix[randomRow][randomCol] = temp; } } return matrix; } public static int[][] shuffle2DArray3(int[][] matrix) { List<Integer> flatList = new ArrayList<>(); // 将二维数组扁平化为一维列表 for (int[] row : matrix) { for (int element : row) { flatList.add(element); } } // 创建随机数生成器 Random r = new Random(42); // 打乱一维列表 Collections.shuffle(flatList, r); // 重新构建二维数组 int rows = matrix.length; int[] cols = new int[rows]; // 记录每一行的列数 for (int i = 0; i < rows; i++) { cols[i] = matrix[i].length; } int[][] shuffledMatrix = new int[rows][]; int index = 0; for (int i = 0; i < rows; i++) { shuffledMatrix[i] = new int[cols[i]]; for (int j = 0; j < cols[i]; j++) { shuffledMatrix[i][j] = flatList.get(index++); } } return shuffledMatrix; } }