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;
}
\$\endgroup\$
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++) {
    …
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.