是否存在用于对此数组进行排序的公式
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
}
}
答案 0 :(得分:3)
您可以这样做:
public static int[][] rearrange(int[][] input) {
int rows = input.length, cols = input[0].length, total = rows * cols;
int[][] output = new int[rows][cols];
for (int i = 0; i < total; i++)
output[i / cols][i % cols] = input[i % rows][i / rows];
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]]
答案 1 :(得分:0)
或者这样:
for (int j = 0, p = 0; j < 7; j++) {
for (int i = 0; i < 3; i++, p++) {
newMatrix[j][i] = oldMatrix[p % 7][p / 7];
}
}