I'm trying to convert a two-dimensional array to a one-dimensional array in Java. I cannot use any additional data structures, ArrayLists, collections etc. for temporary storage. Only one array can be allocated - the one that will be returned from the method.
There are three tests with arrays inputed into the method to validate the program. Test one has a 2D array with 3 rows and columns, test two has a 2D array with 3 rows and 1 column, and test three is empty.
My current code is:
public static int[] twoDConvert(int[][] nums) {
int index = 0;
int[] combined = new int[nums.length*3];
if (nums.length == 0) return combined;
for (int row = 0; row < nums.length; row++) {
for (int col = 0; col < nums.length; col++) {
combined[index] += nums[row][col];
index++;
}
}
return combined;
}
The first test works correctly, but for some reason the 2nd test throws ArrayIndexOutOfBoundsException (Index 1 out of bounds for length 1). This occurs no matter how large or small the combined array length is. How can I fix this?
for (int col = 0; col < nums[row].length; col++) {if (nums.length == 0) return new int[0]; int[] combined = new int[nums.length * nums[0].length];