HavingNoHead
HavingNoHead

Reputation: 119

appending 2 2D arrays without arraycopy

i need to append 2 2D arrays without using arraycopy and by order, first arr1 then arr2, like so:

int[][] arr1 = {{1,2},{7,9,10}};
int[][] arr2 = {{3,5,7,9},{16,10,11}}; 
int[][] arr3 = append(arr1,arr2);
result should be:
1 2 
7 9 10 
3 5 7 9 
16 10 11 

i've tried:

    public static int[][] append(int[][] arr1, int[][] arr2) {
    int [][] arr3 = new int [arr1.length + arr2.length][];
    for (int i=0; i<arr1.length; i=i+1) {
        for (int j=0; j<arr1[i].length; j=j+1) {
            arr3[i][j] = arr1[i][j];
        }
    }
    for (int x=arr1.length; x<arr3.length-2; x=x+1) {
        int a=0;
        for (int y=0; y<arr2[a].length; y=y+1) {
            arr3[x][y] = arr2[a][y];
            a=a+1;
        }
    }
    return arr3;
}

But I'm getting a null pointer exception at line 'arr3[i][j] = arr1[i][j];' What can I do? thanks for the help!!

Upvotes: 2

Views: 52

Answers (2)

Kaplan
Kaplan

Reputation: 3758

You could use streams
(although they are a few ms slower)

int[] array = IntStream.concat(
      IntStream.concat(IntStream.of( arr1[0] ), IntStream.of( arr1[1] )),
      IntStream.concat(IntStream.of( arr2[0] ), IntStream.of( arr2[1] )) )
          .flatMap(IntStream::of).toArray();

to use arr1 and arr2 directly:

Stream.of( arr1, arr2 ).flatMap(Stream::of).flatMapToInt(IntStream::of).toArray();


gets: [1, 2, 7, 9, 10, 3, 5, 7, 9, 16, 10, 11]

Upvotes: 1

Austin Adams
Austin Adams

Reputation: 231

You have two problems:

  1. You are not defining the length of each arr3[i]
  2. You are resetting the a variable each time you go through the second for loop. Declaring it needs to go outside the first loop and incrementing it needs to go outside the second loop (at the end of the first loop).

Change your code to something like this:

public static int[][] append(int[][] arr1, int[][] arr2) {
  int [][] arr3 = new int [arr1.length + arr2.length][];
  for (int i = 0; i < arr1.length; i = i+1) {
    arr3[i] = new int[arr1[i].length];
    for (int j = 0; j < arr1[i].length; j = j+1) {
      arr3[i][j] = arr1[i][j];
    }
  }

  int a = 0;
  for (int x = arr1.length; x < arr3.length; x = x+1) {
    arr3[x] = new int[arr2[a].length];
    for (int y = 0; y < arr2[a].length; y = y+1) {
      arr3[x][y] = arr2[a][y];
    }
    a = a+1;
  }
  return arr3;
}

Upvotes: 1

Related Questions