简体   繁体   中英

Return a column of arrays from a 2D array

Im trying to input a 2D array and return an array that represents the column j of the array of arrays. I get an array out of bounds exception where i defined the int col variable.

When I run this on the multi deminasional array : {{1,3,8}, {4,9,2}, {6,11,14}, {24,6,1}} it returns [1, 1, 1, 1]

public static int[] getColumn(int[][] grid, int j) {
    int[] result = { 0 };
    int row = grid.length;
    int col = grid[row -1].length;

    for (int i = 0; i < col; i++) {
        for (int p = 0; p < row; p++) {
            if (j == i) {
                int[] colJ = new int[row];
                for (int k = 0; k < row; k++) {
                    colJ[k] = grid[p][j];
                }
                result = colJ;
            }

        }

    }
    return result;
}

In Java array indexes start from "0". So, you have to change the cycle: for (int i = 1; i <= col; i++) { to for (int i = 0; i < col; i++) { and for nested cycle as well. For example, if you have 3X3 matrix, left-top element will have index [0][0] and right-bottom element [2][2], but with your implementation you will get [3][3] here: grid[p][j] .

That is my implementation:

public static int[] getColumn(final int[][] grid, final int j) {
    final int index = j - 1; // if we search for 1st element his index is 0, 2nd -> 1, etc.
    final int[] result = new int[grid.length];
    for (int i = 0; i < grid.length; i++) {
        result[i] = grid[i][index]; // take from each sub-array the index we're interesting in
    }
    return result;
}

Output: {3, 9, 11, 6} for grid {{1,3,8}, {4,9,2}, {6,11,14}, {24,6,1}} and j = 2

Change

int col = grid[row].length;

to

int col = grid[row - 1].length;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM