在 Java 中交换数组中的三元组

我正在尝试用 Java 实现以下过程。我有一个数组,其中每个元素都是一个三元组。例如:


int [][] a = { {0,1,0},{1,2,1},{1,0,0},{0,2,0} };

我想交换数组中的每个三元组(与右侧的其他三元组)以获得以下每个矩阵:


b = { {1,2,1},{0,1,0},{1,0,0},{0,2,0} };

c = { {1,0,0},{1,2,1},{0,1,0},{0,2,0} };

d = { {0,2,0},{1,2,1},{1,0,0},{0,1,0} };

e = { {0,1,0},{{1,0,0},{1,2,1},{0,2,0} };

f = { {0,1,0},{0,2,0},{1,0,0},{1,2,1} };

g = { {0,1,0},{1,2,1},{0,2,0},{1,0,0} };

一般来说,对于 k 个三元组的矩阵,有 [(k*(k-1))/2] 种可能的交换。


我该如何解决这个问题?


泛舟湖上清波郎朗
浏览 85回答 1
1回答

鸿蒙传说

双嵌套循环应该在这里工作。请注意,您要求的输出实际上是一个 3D 数组(2D 数组的数组):public int[][] copy2DArray (int[][] input) {&nbsp; &nbsp; int[][] output = new int[input.length][];&nbsp; &nbsp; for (int r=0; r < input.length; ++r) {&nbsp; &nbsp; &nbsp; &nbsp; output[r] = new int[input[r].length];&nbsp; &nbsp; &nbsp; &nbsp; for (int c=0; c < input[0].length; ++c) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output[r][c] = input[r][c];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return output;}public static void main(String[] args) {&nbsp; &nbsp; int [][] a = { {0,1,0},{1,2,1},{1,0,0},{0,2,0} };&nbsp; &nbsp; int numSwaps = a.length*(a.length-1) / 2;&nbsp; &nbsp; int[][][] result = new int[numSwaps][][];&nbsp; &nbsp; int counter = 0;&nbsp; &nbsp; for (int i=0; i < a.length-1; ++i) {&nbsp; &nbsp; &nbsp; &nbsp; for (int j=i+1; j < a.length; ++j) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result[counter] = copy2DArray(a);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int[] temp = result[counter][j];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result[counter][j] = result[counter][i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result[counter][i] = temp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ++counter;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(Arrays.deepToString(result));}这打印:[&nbsp; &nbsp; [[1, 2, 1], [0, 1, 0], [1, 0, 0], [0, 2, 0]],&nbsp; &nbsp; [[1, 0, 0], [1, 2, 1], [0, 1, 0], [0, 2, 0]],&nbsp; &nbsp; [[0, 2, 0], [1, 2, 1], [1, 0, 0], [0, 1, 0]],&nbsp; &nbsp; [[0, 1, 0], [1, 0, 0], [1, 2, 1], [0, 2, 0]],&nbsp; &nbsp; [[0, 1, 0], [0, 2, 0], [1, 0, 0], [1, 2, 1]],&nbsp; &nbsp; [[0, 1, 0], [1, 2, 1], [0, 2, 0], [1, 0, 0]]]对于某些注释,我过去使用的策略是使用两级循环遍历所有位置交换位置for。对于每个可能的交换,我们首先克隆您的输入二维a数组。然后,我们在选择的任何位置交换各个一维数组。最后,我们将该交换数组添加到 3D 结果数组。我们也可以使用类似列表的东西来存储交换的二维数组。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java