0

私は多次元配列を持っています:

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

内部のデータをグリッドとして表示するための単純なループを作成しました。

123
456
789

私が今する必要があるのは、すべてを1つ左にシフトし、グリッドの右側の空のギャップを次のようにゼロに置き換えることです。

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: 
[[I@ece88d2
4

2 に答える 2

2

一見すると、この状況では両端キューのデータ構造が非常に便利だと思います。3行のキュー配列を宣言し、キュー関数を使用して左右にシフトできます。たとえば、右シフトの場合はアイテムをデキューして0をエンキューし、左シフトの場合はもう一方の端から0をデキューしてエンキューすることができます。最初にキューデータ構造を検索し、次に両端キューデータ構造を検索して、最後に関数を実装するか、既存のライブラリを使用してデキュー([ d ] ouble [ e ] nded queueの略)を使用することもできます。) データ構造。このように、配列のサイズは必要な操作を実行するために重要ではありませんが、前述のデータ型(3x3配列)を少し変更する必要があります。

于 2013-02-23T16:49:38.303 に答える
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);
    }

}
于 2017-09-03T11:07:44.167 に答える