在我的java应用程序中,我有一个方法,它返回三个二维数组.All相同大小的行和列。例如,假设这些是我的方法返回的三个二维数组
a=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
现在我想要实现的是创建另一个方法,并再次返回三个二维数组,但是现在第一个二维数组应该有上面每个二维数组的第一行,第二行应该有上面每个二维数组的第二行,所以对于第三个新的二维数组也是如此。
我整天都在想怎么做,但我仍然没有想出任何方法来实现它。如果有人建议我如何做,或者更好地发布一些代码行,我将非常感激,这样我以后就会知道如何继续进行。
发布于 2016-06-16 03:16:35
您必须编写一个方法,在其中为每个数组提供三个原始数组和行长(我建议为每个新的行数组编写不同的方法,以保持代码的整洁),然后只需迭代提供的每个数组。
public int newRowOneArray(int rowLength,int a,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;}
然后,您可以为其他两个新数组编写类似的方法。只需更改与新行对应的每个新方法的行值(例如,第二行的a1
发布于 2016-06-16 03:47:07
我写了一个简单的类来帮助你。它接受一个矩阵列表,其中i (numMatrices) =m(行)=n (cols),并返回一个相同大小的三维数组,其中所有行k都放入矩阵k中,行index =矩阵index。
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("");
}
}
}调用combine()之前
Matrix 1
111
222
333
Matrix 2
111
222
333
Matrix 3
111
222
333调用combine()之后
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];我希望这能帮到你!
https://stackoverflow.com/questions/37843229
复制相似问题