Looks like it has something to do with array initialization, the array
passed to the method does not seem to be 3x3. E.g, following does not produce an Exception:
public static void main(String[] args) throws IOException {
double[][] array = new double[][]{{1d,1d,1d},{2d,2d,2d},{3d,3d,3d}};
double[][] subArray = get2DSubArray(array, 1, 2, 1, 2);
for(double[] arrayElement : subArray){
for(double number : arrayElement){
System.out.println(number);
}
}
}
public static double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex,
int columnEndIndex) {
double[][] subArray = new double[rowEndIndex - rowStartIndex + 1][columnEndIndex - columnStartIndex + 1];
for (int row = rowStartIndex; row < rowEndIndex; row++) {
subArray[row] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex);
}
return subArray;
}
Update
Although the above solution does not produce an Exception, it does not produce correct output as well. Mainly because of the following reasons:
- Third argument for
Arrays.copyOfRange
method is exclusive, so we have to pass columnEndIndex+1
for it to work
- for loop only executes once for provided set of arguments whereas it should execute at least twice
- Instead of assigning
Arrays.copyOfRange
to subArray[row]
, we need to assign it to subArray[<zero based index>]
Below solution does work:
public double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex,
int columnEndIndex) {
double[][] subArray = new double[rowEndIndex - rowStartIndex + 1][columnEndIndex - columnStartIndex + 1];
int index = 0;
for (int row = rowStartIndex; row <= rowEndIndex; row++) {
subArray[index++] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex+1);
}
return subArray;
}