0
public static int[][] add2DArrays(int[][]A, int[][]B) {
        return int[][] C;
}

I understand how to populate this new array by adding the sums of the two arrays A & B, the road block I am facing is creating this initial array C. We cannot assume the size of the arrays given as parameters, so that is the part I am having a problem with.

I know by doing:

 int[][] C = new int[A.length+B.length][]; //this will only give me the # of rows;

I am stuck on how to get the proper length of columns for the rows in the new array. I am thinking it may be possible to some how record the length of the longest row in A, and then record the longest row in B, and choose the bigger of the two, but that seems messy and inefficient. Thank you all for your support.

4
  • Are you trying to create an array where the number of columns is the largest number of columns between A and B, or are you trying to create an array where the number of columns is the sum of the number of columns in A and B? Your question is confusing. Commented Feb 14, 2014 at 23:46
  • I can't press enter on this site for comments without it submitting Commented Feb 14, 2014 at 23:51
  • Think of matrices. The goal is to add Matrix A and Matrix B into a new Matrix C. We do not know the size of the input matrices. Commented Feb 14, 2014 at 23:52
  • Matrix addition requires that the two input matrices have the same dimensions, and the result has the same dimensions as the inputs. You don't add the dimensions in that case. So I still don't know what you're going for. Commented Feb 15, 2014 at 0:06

1 Answer 1

1

If both are really 2D arrays -- that is, the length of all the rows is the same -- and row 0 was actually allocated, you can get the summed length of a row from A[0].length+B[0].length

If the length of the rows might vary -- which is perfectly legal in Java -- then you might need to iterate through A and B to find the longest row and use that length.

Sign up to request clarification or add additional context in comments.

3 Comments

You can also create an array with only the rows size and calculate column size for each row individually
Thanks I appreciate the feedback
@vbazaga86 -- Considered mentioning that, but I didn't think that met the original request. I may have misread it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.