Home > Enterprise >  Slice a column or row from 2d Java Array
Slice a column or row from 2d Java Array

Time:05-31

I'm trying to slice the columns or rows of a 2d Integer Array in Java.

I tried the following syntax array[:][0] or array[0][:] to get the first column/row. I get an error, so most probably this is not the correct syntax in Java. Is it possible to slice in any case a specific column/row in Java?

CodePudding user response:

If I'm not mistaken, slicing in Python corresponds to extracting a subarray from the given array, so if you have an array like below:

int[][] vet = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

Performing the following slicing vet[0:3][1] corresponds to retrieve an array with the elements 2, 5, 8 (second column from row 0 included to row 3 excluded).

Unfortunately, in Java this is not possible, at least not "vertically" since a 2D array is basically an array of arrays. Each "row" index identifies a sub-array but in reality there are now actual rows or columns, just arrays within another array.

What you could do is to use the Arrays.copyOfRange() method to slice an array "horizontally".

Integer[][] vet = new Integer[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Integer[] subArray = new Integer[3];
subArray = Arrays.copyOfRange(vet[1], 0, 3); //Retrieves the elements [4, 5, 6]

Instead, for slicing "vertically" you need to write a utility method:

public static void main(String[] args) {
    Integer[][] vet = new Integer[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    Integer[] subArray = new Integer[3];
    verticalSlicing(vet, subArray, 1, 0, 3);
    System.out.println(Arrays.toString(subArrayVert));  //Prints [2, 5, 8]
}

public static <T> void verticalSlicing(T[][] vet, T[] subArray, int col, int rowStart, int rowEnd) {
    if (col < 0 || col > subArray.length || (rowEnd - rowStart) > subArray.length) {
        return;
    }
    IntStream.range(rowStart, rowEnd).forEach(i -> subArray[i] = vet[i][col]);
}

CodePudding user response:

Usually a 2d array in java will look something like this:

double[][] doubleArray = new double[3][4];

So getting the first row can be:

double[] firstRow = doubleArray[0];

And getting the first column can look like this:

double[] firstColumn = new double[doubleArray.length];
for (int i = 0; i < doubleArray.length; i  ) {
  firstColumn[i] = doubleArray[i][0];
}

CodePudding user response:

Given that you index array[x][y] you can get column x by:

int column[] = array[x].

To get row y:

int row[] = new int[array.length];

for (int i = 0; i < array.length; i  ) {
    row[i] = array[i][y];
}
  • Related