2013-02-23 67 views
0

我有一個多維數組:移多維數組離開

int[][] arrMulti = new int [3][3]; 

我寫了一個簡單的循環,以顯示裏面的數據爲網格:

123 
456 
789 

什麼,我現在需要做的是轉變所有東西都保留一個,並用零替換網格右側的空白間隙,如下所示:

230 
560 
890 

理想的情況是我想的方法能夠轉移任何大小的多維數組,例如

int[][] arrM = new int [28][28] or [98][98] 

是否有人可以幫助我?

謝謝!

這是我到目前爲止的代碼:

package testingarrymove; 


public class TestingArryMove { 

//Start of shift array method 
public static int[][] shiftArray (int arrShiftLeft[][]) { 

int from = 1; 
int to = 0; 

for (int i = 0; i < arrShiftLeft.length; i++) { 
    for (int j = 0; j < arrShiftLeft[0].length; j++) {  


    // move 1 to 0, 2 to 1, 3 to 2, 4 to 3, 5 to 4 ............ 
    System.arraycopy(arrShiftLeft, 1, arrShiftLeft, 0, arrShiftLeft.length - 1); 

    from++; 
    to++; 

     return arrShiftLeft; 
    } 
} 
    return null; 
} // end shiftArray 

public static void main(String[] args) { 

int [][] arrMultiDim = new int [3][3]; 

arrMultiDim [0][0] = 1; 
arrMultiDim [0][1] = 2; 
arrMultiDim [0][2] = 3; 
arrMultiDim [1][0] = 4; 
arrMultiDim [1][1] = 5; 
arrMultiDim [1][2] = 6; 
arrMultiDim [2][0] = 7; 
arrMultiDim [2][1] = 8; 
arrMultiDim [2][2] = 9; 

// outputs original array 
System.out.print("Original Array: "); 
    //loops thought the rows of the array 
    for (int i = 0; i < arrMultiDim.length; i++) { 

     System.out.println(); 
     //loops thought the columns of the array 
     for (int j = 0; j < arrMultiDim[0].length; j++) {  
      System.out.print(" "+arrMultiDim[i][j]); 

     } 

    } 
    System.out.println(); 

    System.out.println("Shifted Array: "); 
    //this should copy just the row to another array by calling the shiftedArray 
    shiftArray(arrMultiDim); 
    //outputs the shifted array 
    System.out.println(arrMultiDim); 
} 

} // end class 

我已經試過system.arraycopy。以上代碼輸出:

Original Array: 
1 2 3 
4 5 6 
7 8 9 
Shifted Array: 
[[[email protected] 

回答

2

乍一看,我認爲雙端隊列數據結構在這種情況下非常方便。您可以聲明一個具有3行的隊列數組,並使用隊列函數左右移動。例如,您可以將某個項目出列,並向右移入0,並從另一端出列並排隊0以進行左移。你可能首先要查找the queue data structure然後the double eneded queue data structure,最終實現的功能,甚至使用現有的庫來使用dequeue(代表[d] ouble [ë] nded 隊列)數據結構。通過這種方式,數組的大小無關緊要地執行操作,但您必須稍微更改所提到的數據類型(3x3數組)。

0
public static void shift(int[][] arr, int offs) { 
    if (offs <= 0) 
     return; 

    offs = offs > arr[0].length ? arr[0].length : offs; 

    for (int[] row : arr) { 
     if (offs < arr.length) 
      System.arraycopy(row, offs, row, 0, row.length - offs); 
     Arrays.fill(row, row.length - offs, arr.length, 0); 
    } 

}