10

Suppose I have 2D array as follow:

int[][] temp={
              {1,2,3,4},
              {5,6,7,8},
              {9,10,11,12}};

and i want to get sub-array start from X direction 1 to 2 and Y direction 1 to 2 i.e.

{6,7}
{10,11}

can anyone give me solution for above problem.

Somnath Kadam
  • 6,051
  • 6
  • 21
  • 37

3 Answers3

10

Here you are

    int[][] temp = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
    int[][] a = new int[temp.length][];
    for (int i = 0; i < temp.length; i++) {
        a[i] = Arrays.copyOfRange(temp[i], 1, 3);
    }
    System.out.println(Arrays.deepToString(a));

output

[[2, 3], [6, 7], [10, 11]]

answering your question in comment if we want to access only [[6, 7], [10, 11]]

    int[][] a = new int[2][];
    for (int i = 1, j = 0; i < 3; i++, j++) {
        a[j] = Arrays.copyOfRange(temp[i], 1, 3);
    }

output

[[6, 7], [10, 11]]
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • 1
    but if we want to access only [[6, 7], [10, 11]] then? – Somnath Kadam May 03 '13 at 16:01
  • My array is like this, 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 and Im getting output like this [[0, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0]] when I use int[][] data = Arrays.copyOfRange(array, 1, 3); System.out.println(Arrays.deepToString(data)); I want like [[0,1],[1,1]]... Is there any way? – Narendra Mar 19 '17 at 06:13
1

As an example without using the Arrays class:

int[][] temp = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
int[][] subArray = new int[temp.length][];
for (int i = 0; i < subArray.length; i++) {
    subArray[i] = new int[2];
    subArray[i][0] = temp[i][1];
    subArray[i][1] = temp[i][2];
}

You can then access any part of subArray that you want. This will access the values [[6, 7], [10, 11]]:

for (int x = 1; x < 3; x++) {
    System.out.println(subArray[x][0]);
    System.out.println(subArray[x][1]);
}

[Additional] To address the modified question:

If you want to create a smaller array you can play around with the start and end points of the loop, and the indices accessed within the loop, for example this will create the array you ask for:

int[][] subArray = new int[2][];
for (int i = 1; i < temp.length; i++) {
    subArray[i-1] = new int[2];
    subArray[i-1][0] = temp[i][1];
    subArray[i-1][1] = temp[i][2];
}
Matt Hyde
  • 1,572
  • 1
  • 13
  • 17
0

You could instantiate a new array and loop through the appropriate indices of the original array to initialize the subarray.

John
  • 15,990
  • 10
  • 70
  • 110
  • Which would be a faster solution? The ones provided above or iteration approach runtime wise? – kauray Apr 09 '18 at 08:11