镜像二维阵列



嗨,我正在尝试制作一个代码,它采用2d数组并镜像它,

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

我做错了什么。。?

您正在反转数组的第一个维度("行"),而不是第二个维度(("列")。

您需要将镜像中的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;
    }
  }
}

最新更新