2013-05-13 17 views
-3

我需要翻轉一個一維64個元素的短褲數組(如果它更簡單,我可以切換爲整數,但我假定使用相同的過程將可以用於Java)。爲了便於理解,我在此將其表示爲方桌,因爲實際問題在棋盤上。如何翻轉代表Java中二維數組的一維short/int數組中的行

例如:

short[] example = new short[] 
{ 
    1, 2, 3, 
    4, 5, 6, 
    7, 8, 9 
}; 

將成爲:

7 8 9 
4 5 6 
1 2 3 

請注意,這是一樣的倒車,我發現已經使此陣列(每個回答者到類似的問題錯誤,因此我不得不問!)。扭轉陣列將給:

9 8 7 
6 5 4 
3 2 1 

道歉,如果我錯過了任何重要的信息,任何幫助表示讚賞!

編輯:該數組是1D,幷包含64個元素,如此短[64],而反向陣列是獨立於原來的。至於我所嘗試的,我只是在努力圍繞它而努力。我知道如何扭轉陣列,但是這不是我後,我原本試圖扭轉使用索引:這是一段代碼我在Chessbin發現

byte index = (byte)(((byte)(position + 56)) - (byte)((byte)(position/8) * 16)); 

,但是這將返回不正確的值並給出IndexOutOfBounds錯誤。事後看來,我不清楚這些代碼是爲了翻轉索引還是反轉索引。由於數學不是我的強項,我試圖用單獨的數組解決它。

+12

你已經錯過了你已經嘗試 – 2013-05-13 18:07:02

+3

這個數組在代碼中看起來像什麼?它是否短[] []'?你有沒有嘗試過任何東西?有錯誤嗎? – thegrinner 2013-05-13 18:08:26

+1

這是一個多維數組 ? – Adarsh 2013-05-13 18:09:52

回答

0

你有一個物理的一維數組表示一個邏輯2D數組,並且你想交換行。您可以通過將二維數組索引映射到一維數組索引來完成此操作。

height爲行數,width爲列數。

for (int i = 0; i < height/2; ++i) { 
    int k = height - 1 - i; 
    for (int j = 0; j < width; ++j) { 
     short temp = array[i * width + j]; 
     array[i * width + j] = array[k * width + j]; 
     array[k * width + j] = temp; 
    } 
}  

我已經寫了這個可讀性。您或編譯器可能會優化一些重複的計算。

您可能能夠通過使用二維數組,這樣可以讓你交換引用行的O(高度)進一步優化,而不是爲O複製所有行(高*寬)。

2

我的建議是這樣的:

public class Flipper { 

    public short[] flip(short[] array, int columns) { 
     short[] flipped = new short[array.length]; 
     for(int i=0;i<array.length;i++){ 
      int row = (i/columns); //use the fact that integer/integer is rounded down 
      int column = (i%columns); 
      flipped[i] = array[array.length-((columns*(row+1))-column)]; 
     } 
     return flipped; 
    } 

} 

可與測試:

public class FlipperTest { 

    private Flipper flipper = new Flipper(); 

    @Test 
    public void test() { 
     short[] array = new short[]{1,2,3,4,5,6,7,8,9}; 
     short[] actualResult = flipper.flip(array, 3); 
     assertThat(actualResult, equalTo(new short[]{7,8,9,4,5,6,1,2,3})); 
    } 

} 

希望的代碼是不言自明

+1

對於單循環解決方案+1。不在位,但可以很容易地在原地進行。我的可讀性較差。注意:「行」是基於1的,而「列」是基於0的;在代碼中值得一提,最好是變量名,或者至少是在線文檔。 – 2013-05-13 19:34:32

+0

@Andy Thomas-Cramer - 同意,回答改善 – macias 2013-05-13 19:51:09