[英]Mirroring 2D Arrays
嗨,我正在嘗試制作一個采用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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.