我正在编写一个程序来尽可能高效地乘以矩阵(二维数组),为此我需要将两个数组分成两个,然后将它们发送到第二个程序进行乘法。我遇到的问题是如何在特定点(中间)将一个二维数组拆分为两个二维数组。有人有什么想法吗?
最佳答案
假设你有一个像这样的二维字符串数组
String[][] array= new String[][]
{
{"a","b","c"},
{"d","e","f"},
{"h","i","j"},
{"k","l","m"}
};
现在您需要一种方法在中间点分割这些数组。让我们得到中间点。计算出数组有多大,然后将其切成两半。请注意,如果数组长度不是偶数,您还必须处理。例如,长度为 3。如果是这种情况,我们将使用 Math.floor()
功能。
int arrayLength = array.length;
int halfWayPoint = Math.floor(arrayLength/2);
//we also need to know howmany elements are in the array
int numberOfElementsInArray = array[0].length;
现在我们拥有了从一个二维数组创建两个二维数组所需的所有信息。现在我们必须显式地复制创建并复制数据。
//the length of the first array will be the half way point which we already have
String [][] newArrayA = new String[halfWayPoint][numberOfElementsInArray];
//this copies the data over
for(int i = 0; i < halfWayPoint; i++)
{
newArrayA[i] = array[i];
}
//now create the other array
int newArrayBLength = array.length - halfWayPoint;
String[][] newArrayB = new String[newArrayBLength][numberOfElementsInArray];
/*
* This copies the data over. Notice that the for loop starts a halfWayPoint.
* This is because this is where we left of copying in the first array.
*/
for(int i = halfWayPoint; i < array.length; i++)
{
newArrayB[i] = array[i];
}
你完成了!
现在如果你想做得更好一点,你可以这样做
int half = Math.floor(array/2);
int numberOfElementsInArray = array[0].length;
String [][] A = new String[half][numberOfElementsInArray];
String [][] B = new String[array.length - half][numberOfElementsInArray];
for(int i = 0; i < array.length; i++)
{
if(i < half)
{
A[i] = array[i];
}
else
{
B[i] = array[i];
}
}
最后,如果您不想显式执行此操作,可以使用内置函数。 System.arraycopy()
就是一个例子。这是其 api 的链接 System.arraycopy()
int half = Math.floor(array/2);
int numberOfElementsInArray = array[0].length;
String [][] A = new String[half][numberOfElementsInArray];
String [][] B = new String[array.length - half][numberOfElementsInArray];
System.arraycopy(array,0,A,0,half);
System.arraycopy(array,half,B,0,array.length - half);
关于java:如何将二维数组拆分为两个二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5463781/