2016-06-15 19 views
0

在我的Java應用程序,我有我返回三個二維陣列。所有的行和列的同樣大小的方法的每個i行。例如,讓假設這些是我的三個二維陣列,其我的方法返回如何Concat的一個二維陣列的每個i行與另一二維數組

一個= [2,4,5,18 9,4,1,7 14,67,90,2]

b = [34,23,1,9 12,5,9,0 14,67,8,1]

C = [2,68,1,1 3,7,0,11 23 ,45,5,5]

現在我想實現的是TI創建另一個方法,並再次返回三個二維陣列,但現在第一二維數組應該有第一列F從上面的每個二維數組開始,第二行應該有每個二維數組的第二行,以及第三個新的二維數組。

我想了一整天怎麼做,但我還是沒弄明白什麼辦法如何去實現它。我會很感激,如果有人建議我該怎麼做或更好的發佈代碼的某些行,所以我會有任何想法如何繼續以後

回答

0

你不得不寫在你提供你的三個原始陣列的方法和行長度(我建議爲每個新行數組寫一個不同的方法,保持代碼更清晰),然後遍歷每個提供的數組。

公共INT [] [] newRowOneArray(INT rowLength,INT [] []一,INT [] [] B,INT [] [] C){

int returnArray[] [] = new int[3][rowLength]; //new 2d array 

for(int i=0; i<rowLength; i++){ 
     returnArray[0][i] = a[0][i]; //place a row one in new row 1 
} 

for(int i=0; i<rowLength; i++){ 
     returnArray[1][i] = b[0][i]; //place b row one in new row 2 

} 

for(int i=0; i<rowLength; i++){ 
     returnArray[2][i] = c[0][i]; //place c row one in new row 3 

} 

return returnArray; 

}

然後您可以爲其他兩個新陣列編寫類似的方法。只要改變該行的值(例如,[1] [I]爲連續兩個),用於與新行

+0

我很困惑你爲什麼給出了一維數組而不是二維類型的方法的返回類型?我想它可能是錯誤的輸入,因爲當你返回時,你返回一個二維數組。我是對的 –

+0

是的,它應該是返回的二維數組。我的返回類型對我來說很合適,但也許我打錯了。 –

+0

這是完全正確的,但我真正想要的是,我有n - 二維數組不僅a,b,c和k行每個n - 二維數組,因此我不能把方法的參數int [] [ ] a,int [] [] b,int [] [] c因爲我會有更多。有沒有辦法如何做到這一點? :( –

0

對應的每一個新的方法,我寫了一個簡單的類來幫助你。它包含一個矩陣列表[i] [m] [n],其中i(numMatrices)= m(rows)= n(cols)並返回一個相同大小的三維數組,並將所有行k放入矩陣k的行指數=矩陣指數。

public class MatrixManipulator { 

    public int[][][] combine(int[][][] matrices) { 

     // We are making a lot of assumptions here by not checking 
     // that dimension are equal (cubic for this problem) 
     final int numMatrices = matrices.length, numRows = matrices[0].length, numColumns = matrices[0][0].length; 

     int[][][] newMatrices = new int[numMatrices][numRows][numColumns]; 

     for (int i = 0; i < numMatrices; ++i) { 
      for (int m = 0; m < numRows; ++m) { 
       for (int n = 0; n < numColumns; ++n) { 
        newMatrices[i][m][n] = matrices[n][m][i]; 
       } 
      } 
     } 
     return newMatrices; 
    } 

    public void printMatrices(int[][][] matrices) { 
     final int numMatrices = matrices.length, numRows = matrices[0].length, numColumns = matrices[0][0].length; 

     for (int i = 0; i < numMatrices; ++i) { 
      System.out.println("Matrix " + (i + 1)); 
      for (int m = 0; m < numRows; ++m) { 
       for (int n = 0; n < numColumns; ++n) { 
        System.out.print(matrices[i][n][m]); 
       } 
       System.out.println(""); 
      } 
      System.out.println(""); 
     } 
    } 
} 

之前調用合併()

Matrix 1 
111 
222 
333 

Matrix 2 
111 
222 
333 

Matrix 3 
111 
222 
333 

調用組合(後)

Matrix 1 
111 
111 
111 

Matrix 2 
222 
222 
222 

Matrix 3 
333 
333 
333 

請我實現矩陣存儲爲列的列表頭腦。對於一些人來說,存儲行列表可能更直觀。爲了讓行的列表來工作,你只需要這一行的改變:

newMatrices[i][m][n] = matrices[n][m][i]; 

newMatrices[i][m][n] = matrices[m][i][n]; 

我希望這有助於!

- Tom

相關問題