我有一个代码可以创建一个2dimantional数组,它可以正常工作,但现在我想让第一行成为反向的最后一行。
就像你有一个专栏
1
2
3
4
必须像这样进入新阵列:
4 3 2 1
我拥有的矩阵是:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
新矩阵必须如下:
16 12 8 4
15 11 7 3
14 10 6 2
13 9 5 1
这是我的代码:
package test5;
public class test5 {
public static void main(String[] args) {
int[][] nums = new int[4][4];
nums[0][0] = 1;
nums[0][1] = 2;
nums[0][2] = 3;
nums[0][3] = 4;
nums[1][0] = 5;
nums[1][1] = 6;
nums[1][2] = 7;
nums[1][3] = 8;
nums[2][0] = 9;
nums[2][1] = 10;
nums[2][2] = 11;
nums[2][3] = 12;
nums[3][0] = 13;
nums[3][1] = 14;
nums[3][2] = 15;
nums[3][3] = 16;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
System.out.print(nums[i][j] + " ");
}
System.out.println();
}
}
}
所以任何人都可以帮助我???
答案 0 :(得分:0)
如果您需要自己动手,请尝试以下方法:
public class MatrixTranspose {
static int m1[][] = new int[][]{{1, 2, 3, 4, 5}, {5, 6, 7, 8, 9}, {9, 10, 11, 12, 13}, {13, 14, 15, 16, 17}};
public static String toString(int[][] m) {
StringBuilder text = new StringBuilder();
for (int row = 0; row < m.length; row++) {
int r[] = m[row];
for (int col = 0; col < r.length; col++) {
if (col > 0) text.append(", ");
text.append(r[col]);
}
text.append("\n");
}
return text.toString();
}
public static int[][] transpose(int[][] m) {
int rows = m.length;
int cols = m[0].length;
int t[][] = new int[cols][]; // first create the empty transpose matrix
for (int trow = 0; trow < cols; trow++) {
t[trow] = new int[rows];
}
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
int tcol = rows-row-1; // transposed tcol is inverted row
int trow = cols-col-1; // transposed trow is inverted col
t[trow][tcol] = m[row][col];
}
}
return t;
}
public static void main(String...params) {
System.out.println(toString(m1));
System.out.println("--");
System.out.println(toString(transpose(m1)));
}
}