镜像二维数组

Mirroring 2D Arrays

你好,我正在尝试制作一个采用二维数组并像这样镜像它的代码,

input:        and get the output like so:  
  123                                      321
  456                                      654
  789                                      987

我有这部分代码:

public static void mirror(Object[][] theArray) {
    for(int i = 0; i < (theArray.length/2); i++) {
        Object[] temp = theArray[i];
        theArray[i] = theArray[theArray.length - i - 1];
        theArray[theArray.length - i - 1] = temp;
    }
}
}

我的程序运行正常,但它返回相反的结果

input:        and get the output like so:  
  123                                      789
  456                                      456
  789                                      123

我做错了什么..?

您正在反转数组的第一个维度('rows'),而不是第二个维度('columns')。

需要将mirror中的for循环包裹在另一个for循环中,并适当调整索引。

public static void mirror(Object[][] theArray) {
  for (int j = 0; j < theArray.length; ++j) {  // Extra for loop to go through each row in turn, performing the reversal within that row.
    Object[] row = theArray[j];
    for(int i = 0; i < (row.length/2); i++) {
        Object temp = row[i];
        row[i] = theArray[j][row.length - i - 1];
        row[row.length - i - 1] = temp;
    }
  }
}