[Programmers / JAVA] Level 1 Matrix Addition (12950)
[Programmers / JAVA] Level 1 Matrix Addition (12950)
Matrix addition takes two matrices of equal number of rows and columns, and produces a result by adding the values at the same row and same column. Given two matrices arr1 and arr2, complete the function solution that returns the result of the matrix addition.
@RWBwritten at 2021-12-18 12:56:29
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
Matrix addition takes two matrices of equal number of rows and columns, and produces a result by adding the values at the same row and same column. Given two matrices arr1 and arr2, complete the function solution that returns the result of the matrix addition.
- The number of rows and columns of matrices arr1 and arr2 does not exceed 500.
| arr1 | arr2 | return |
|---|---|---|
| { { 1, 2 }, { 2, 3 } } | { { 3, 4 }, { 5, 6 } } | { { 4, 6 }, { 7, 9 } } |
| { { 1 }, { 2 } } | { { 3 }, { 4 } } | { { 4 }, { 6 } } |
We need to compute the sum of matrices, that is, of 2-dimensional arrays. Simply loop through with a nested loop, adding each element and returning the result.
JAVA
/** * Matrix Addition class * * @author RWB * @since 2021.12.13 Mon 22:12:23 */ class Solution { /** * Method that returns the answer * * @param arr1: [int[][]] matrix 1 * @param arr2: [int[][]] matrix 2 * * @return [int[][]] answer */ public int[][] solution(int[][] arr1, int[][] arr2) { int[][] answer = new int[arr1.length][arr1[0].length]; for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr1[i].length; j++) { answer[i][j] += arr1[i][j] + arr2[i][j]; } } return answer; } }
# Programmers# Algorithm# JAVA# Level 1
