Reputation: 107
I would like to send certain columns of a 2D array to another method as a 2D array. For example, I have the following array:
1 2 6 4
2 5 3 9
2 5 1 3
I would like to send lets say the middle 2 columns to a method as the 2D array:
2 6
5 3
5 1
How would I split this in a way that I could clarify the amount of columns being split and where I want the split to start and end. My understanding is that System.arrayCopy()
would be an efficient way of performing this, however, I can only copy a 1D array with it.
Upvotes: 0
Views: 1136
Reputation: 109597
There is a lesson in this.
It is easier to pick out a couple of rows of a two dimensional array. So maybe represent columns as rows.
int[][] arr = {
{1, 2, 2},
{2, 5, 5},
{6, 3, 1},
{4, 9, 3}
};
int[][] sub = new int[] {
Arrays.copyOf(arr[1], 3),
Arrays.copyOf(arr[2], 3)
};
int[][] sharing = Arrays.copyOfRange(arr, 1, 3); // 3 exclusive.
The last sharing
shares the rows (columns) with arr
.
One could make one's matrix class.
There is a story behind this. The Asian soroban is 90° rotated with respect to the Roman abacus. This makes it more readable IMHO, as reading numbers, and the soroban indeed is still a good pedagogical and useful tool.
Utilities: Arrays.copyOfRange(T[],int,int)
.
Upvotes: 2
Reputation:
To get a 2d sub-array from an existing 2d array - you can iterate over the rows of this array, and for each row, iterate over the specified range using the Arrays.stream(int[],int,int)
method:
int[][] arr1 = {
{1, 2, 6, 4},
{2, 5, 3, 9},
{2, 5, 1, 3}};
int[][] arr2 = Arrays.stream(arr1)
// range from '1' inclusive to '3' exclusive
.map(row -> Arrays.stream(row, 1, 3).toArray())
.toArray(int[][]::new);
// output
Arrays.stream(arr2).map(Arrays::toString).forEach(System.out::println);
[2, 6]
[5, 3]
[5, 1]
Upvotes: 1
Reputation: 17900
Try this.
int[][] arr = new int[][]{
{1, 2, 6, 4},
{2, 5, 3, 9},
{2, 5, 1, 3}
};
int startColumn = 1;
int endColumn = 2;
int[][] result = Arrays.stream(arr)
.map(row -> IntStream.rangeClosed(startColumn, endColumn)
.map(j -> row[j]).toArray())
.toArray(int[][]::new);
System.out.println(Arrays.deepToString(res));
Output: [[2, 6], [5, 3], [5, 1]]
It streams the 2D array and for each row, it builds a 1D array by picking the columns from startColumn
to endColumn
inclusive and collects every array in a 2D array.
Upvotes: 2