是否有以这种方式重新排列二维数组的公式?

有没有公式可以对这个数组进行排序


 1  2   3

 4  5   6

 7  8   9

 10 11  12

 13 14  15

 16 17  18

 19 20  21


1   4   7

10  13  16

19  2   5

8   11  14

17  20  3

6   9   12

15  18  21

取第一列并将其放在二维数组中的第一个位置


这些是您重新定位后的位置


[0][0] --> [0][0]

[1][0] --> [0][1]

[2][0] --> [0][2]

[3][0] --> [1][0]

[4][0] --> [1][1]

[5][0] --> [1][2]

[6][0] --> [2][0]

[0][1] --> [2][1]

[1][1] --> [2][2]

[2][1] --> [3][0]

[3][1] --> [3][1]

[4][1] --> [3][2]

[5][1] --> [4][0]

[6][1] --> [4][1]

[0][2] --> [4][2]

[1][2] --> [5][0]

[2][2] --> [5][1]

[3][2] --> [5][2]

[4][2] --> [6][0]

[5][2] --> [6][1]

[6][2] --> [6][2]

我可以看到模式,但想不出公式


我想用这个,如果我是对的


 for(int i = 0 ; i < 3 ; i++){

   for(int j = 0 ; j < 7 ; j++){

       //do something here

   }

 }


哈士奇WWW
浏览 139回答 2
2回答

守着星空守着你

你可以这样做:public static int[][] rearrange(int[][] input) {&nbsp; &nbsp; int rows = input.length, cols = input[0].length, total = rows * cols;&nbsp; &nbsp; int[][] output = new int[rows][cols];&nbsp; &nbsp; for (int i = 0; i < total; i++)&nbsp; &nbsp; &nbsp; &nbsp; output[i / cols][i % cols] = input[i % rows][i / rows];&nbsp; &nbsp; return output;}测试int[][] input = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {13, 14, 15}, {16, 17, 18}, {19, 20, 21}};System.out.println(Arrays.deepToString(rearrange(input)));输出[[1, 4, 7], [10, 13, 16], [19, 2, 5], [8, 11, 14], [17, 20, 3], [6, 9, 12], [15, 18, 21]]

RISEBY

或者像这样:&nbsp; &nbsp; for (int j = 0, p = 0; j < 7; j++) {&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < 3; i++, p++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newMatrix[j][i] = oldMatrix[p % 7][p / 7];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java