Given two jagged arrays: a & b where a + b will always have the same # of rows:
int[][] a = { {1,2}, {4,5,6} };
int[][] b = { {7}, {8,9,0} };
how exactly can I manipulate a new jagged array c to return:
{ {1,2,7}, {4,5,6,8,9,0} }
?
Here's what I have so far:
int[][] c = null;
for(int i = 0; i<a.length; i++){
c = new int[a.length][a[i].length + b[i].length];
}
//rest of my code for assigning the values into the appropriate position works.
The trouble arises, as you all can see, that I am performing a deep copy, which, on the second iteration of the for-loop, is setting ALL rows to a length of the length of the current row on the step of the iteration.
You are creating a new 2D array object each iteration of your loop. Each time through, you are reassigning c
, thus throwing out all of your previous work. Additionally, placing a number in both set of brackets at the same time results in each row having the same length.
Using your example, the first time through the loop, c
is assigned to a 2D array with two rows, each of length three. The second time through the loop, you throw out your previous 2D array and create a new one having two rows, each of length six.
But what you need to be doing is creating a new row each time through the loop, not the entire 2D array.
First, we create a 2D array called c
and specify that it has a.length
rows. We don't put a value in the second bracket, because that would indicate that all of the rows are of the same length. So at this point, c
does not know about row length. It just knows how many rows it can have. Keep in mind: c
doesn't actually have any rows yet, just a capacity for a.length
rows.
Next, we must create the rows and assign a length/capacity to them. We set up our loop to run as many times as there are rows. The current row index is denoted by i
, and therefore, c[i]
refers to a specific row in the 2D c
array. We use new int[]
to create each individual row/array, but inside the brackets, we must specify the length of the current row. For any row c[i]
, its length is given by the sum of the lengths of a[i]
and b[i]
; that is, a[i].length + b[i].length
.
What we are left with is an array c
that contains rows/arrays, each with a set length/capacity that matches the sum of the corresponding rows lengths in a
and b
.
Keep in mind that c
still does not contain any integer values, only containers that are of the correct size to hold the values in a
and b
. As you mentioned, you already have code to populate your array with values.
int[][] c = new int[a.length][];
for (int i = 0; i < a.length; i++) {
c[i] = new int[a[i].length + b[i].length];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With