2
\$\begingroup\$

For a homework assignment, I was asked to do this problem. It worked, but it looks messy in my opinion. I want to know if this is the best way to accomplish this task, and if there can be any improvements made to this code, such as efficiency and code compactness. The assignment is explained below:

Write a method named matrixSum that accepts as parameters two 2D arrays of integers, treats the arrays as 2D matrices and adds them, returning the result. The sum of two matrices A and B is a matrix C where for every row i and column j, Cij = Aij + Bij. You may assume that the arrays passed as parameters have the same dimensions.

A = { { 1, 2, 3 }, { 4, 4, 4 } }

B = { { 5, 5, 6 }, { 0, -1, 2 } }

maxtrixSum(a, b) => { { 6, 7, 9 }, { 4, 3, 6 } }

My Solution

public int[][] matrixSum(int[][] a, int[][] b) {
 if(a.length == 0 || b.length == 0) { return new int[0][0]; }
 int[][] sum = new int[a.length][a[0].length];
 //Can use just `a` for length because a & b have the same dimensions
 for(int i = 0; i < a.length; i++) {
 for(int j = 0; j < a[0].length; j++) {
 sum[i][j] = a[i][j] + b[i][j];
 }
 }
 return sum;
}
asked May 17, 2019 at 18:25
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Your code is pretty much a straightforward textbook solution. Good job on handling the zero-size matrix case, so that a[0].length doesn't cause a crash.

It's more conventional to put a space after flow-control keywords like if and for, so that they look less like function calls:

for (int i = 0; i < a.length; i++) {
 ...
}
answered May 17, 2019 at 19:21
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.