I am trying to implement Strassen's Algorithm in Java and I am at a step where I need to combine the output into a single matrix/2D array. I am using System.arraycopy
to copy the arrays, which works well for concatenating two arrays in a top-down manner, however, I also need to concatenate them side-by-side and I am having trouble with that. I run into ArrayOutOfBoundsException
. Here is my code
static int[][] Consolidate(int[][] c11, int[][] c12, int[][] c21, int[][] c22) {
/* check size compatibility */
if(c11[0].length == c21[0].length &&
c11.length == c12.length &&
c21.length == c22.length &&
c22[0].length == c12[0].length) {
int _rowSize = c11.length + c21.length;
int _colSize = c11[0].length + c12[0].length;
int[][] retArray = new int[_rowSize][_colSize];
int[][] ltArray = new int[_rowSize][c11[0].length];
int[][] rtArray = new int[_rowSize][c12[0].length];
System.arraycopy(c11, 0, ltArray, 0, c11.length);
System.arraycopy(c21, 0, ltArray, c11.length, c21.length);
System.arraycopy(c12, 0, rtArray, 0, c12.length);
System.arraycopy(c22, 0, rtArray, c12.length, c22.length);
System.arraycopy(ltArray, 0, retArray, 0, ltArray.length);
System.arraycopy(rtArray, 0, retArray, ltArray.length, rtArray.length);
return retArray;
}
return null;
}
The last line
System.arraycopy(rtArray, 0, retArray, ltArray.length, rtArray.length);
Throws the exception. Is there a way to concatenate Arrays side-by-side (in the column-wise manner)?
EDIT Here is the verified answer
You can copy the last part manually.
Replace
System.arraycopy(ltArray, 0, retArray, 0, ltArray.length);
System.arraycopy(rtArray, 0, retArray, ltArray.length, rtArray.length);
With
//Commented both calls
//System.arraycopy(ltArray, 0, retArray, 0, ltArray.length);
//System.arraycopy(rtArray, 0, retArray, ltArray.length, rtArray.length);
for (int row = 0; row < ltArray.length; row++) {
int colInTarget = 0;
for (int col = 0; col < ltArray[row].length; col++,colInTarget++) {
retArray[row][colInTarget] = ltArray[row][col];
}
for (int col = 0; col < rtArray[row].length; col++,colInTarget++) {
retArray[row][colInTarget] = rtArray[row][col];
}
}