물음표 살인마의 개발블로그

알고리즘 문제/CodeWar

Matrix Addition

BEstyle 2022. 10. 24. 13:21

DESCRIPTION:

Write a function that accepts two square matrices (N x N two dimensional arrays), and return the sum of the two. Both matrices being passed into the function will be of size N x N (square), containing only integers.

How to sum two matrices:

Take each cell [n][m] from the first matrix, and add it with the same [n][m] cell from the second matrix. This will be cell [n][m] of the solution matrix.

Visualization:

|1 2 3|     |2 2 1|     |1+2 2+2 3+1|     |3 4 4|
|3 2 1|  +  |3 2 3|  =  |3+3 2+2 1+3|  =  |6 4 4|
|1 1 1|     |1 1 3|     |1+1 1+1 1+3|     |2 2 4|

Example

matrixAddition(
  [ [1, 2, 3],
    [3, 2, 1],
    [1, 1, 1] ],
//      +
  [ [2, 2, 1],
    [3, 2, 3],
    [1, 1, 3] ] )

// returns:
  [ [3, 4, 4],
    [6, 4, 4],
    [2, 2, 4] ]

def matrix_addition(a, b):
    alist=a.copy()
    length=(len(a))
    for i in range(length):
        for j in range(length):
            alist[i][j]=a[i][j]+b[i][j]
    return alist

'알고리즘 문제 > CodeWar' 카테고리의 다른 글

New Cashier Does Not Know About Space or Shift  (0) 2022.10.25
Decipher this!  (0) 2022.10.25
Length of missing array  (0) 2022.10.24
Kebabize  (0) 2022.10.24
Pascal's Triangle  (0) 2022.10.21