blog.itcode.devblog.itcode.dev

[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.

[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.
RWB0104
@RWBwritten at 2021-12-18 12:56:29
Programmers

시리즈 모아보기

Programmers

62 / 78
RankLanguage Used
Level 1

🖼️ JAVA

🔗 Matrix Addition

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.
arr1arr2return
{ { 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
ship
blog.itcode.dev

Notes from the π-th Alpaca

7.0.1
Developed by RWB since 2021.057th upgraded at 2026.08