Convert two dimensional array to one dimensional array in Java

Goobla :

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?

Jason :

We create a single Integer array with a length determines by the size method. Size takes the 2-dimensional array and finds the sum of all columns in each row and returns that sum. We check if the length is 0, and if so, we return. We then loop through all rows, followed by a loop through all columns in that row. We then assign the value at that row and column to that next index in the array. Unfortunately we can't do any math (to my knowledge) to determine the index based of row/column since they could be variable sizes.

    public static int[] twoDConvert(int[][] nums) {
        int[] combined = new int[size(nums)];

        if (combined.length <= 0) {
            return combined;
        }
        int index = 0;

        for (int row = 0; row < nums.length; row++) {
            for (int column = 0; column < nums[row].length; column++) {
                combined[index++] = nums[row][column];
            }
        }
        return combined;
    }

    private static int size(int[][] values) {
        int size = 0;

        for (int index = 0; index < values.length; index++) {
            size += values[index].length;
        }
        return size;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=169015&siteId=1