행렬의 곱셈
https://school.programmers.co.kr/learn/courses/30/lessons/12949
📔 문제 설명
2차원 행렬 arr1과 arr2를 입력받아, arr1에 arr2를 곱한 결과를 반환하는 함수, solution을 완성해주세요.
💡 입출력 예
arr1 | arr2 | return |
---|---|---|
[[1, 4], [3, 2], [4, 1]] | [[3, 3], [3, 3]] | [[15, 15], [15, 15], [15, 15]] |
[[2, 3, 2], [4, 2, 4], [3, 1, 4]] | [[5, 4, 3], [2, 4, 1], [3, 1, 1]] | [[22, 22, 11], [36, 28, 18], [29, 20, 14]] |
💻내가 작성한 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function solution(arr1, arr2) {
const answer = [];
for (const arr1Row of arr1) {
const arr = [];
for (let arr2Col = 0; arr2Col < arr2[0].length; arr2Col++) {
let sum = 0;
for (let arr1Col = 0; arr1Col < arr1Row.length; arr1Col++) {
const arr1Num = arr1Row[arr1Col];
const arr2Num = arr2[arr1Col][arr2Col];
sum += arr1Num * arr2Num;
}
arr.push(sum);
}
answer.push(arr);
}
return answer;
}
💻다른 사람 코드
1
2
3
4
5
6
7
8
9
function productMatrix(A, B) {
return A.map(function (row) {
return row.map(function (_, i) {
return row.reduce(function (sum, cell, j) {
return sum + cell * B[j][i];
}, 0);
});
});
}
This post is licensed under CC BY 4.0 by the author.