题解 | #矩阵乘法#
矩阵乘法
https://www.nowcoder.com/practice/ebe941260f8c4210aa8c17e99cbc663b
function genMatrix(x, y) { return Array.from(new Array(x), () => new Array(y).fill(0)); } function getItemSum(arrX, arrY) { return arrX.reduce((sum, cur, index) => { return sum += cur * arrY[index]; }, 0); } const m1x = parseInt(readline(), 10); const m1y = m2x = parseInt(readline(), 10); const m2y = parseInt(readline(), 10); const m1 = genMatrix(m1x, m1y); const m2 = genMatrix(m2x, m2y); const res = genMatrix(m1x, m2y); let index = 0; let m = m1; let lines; while (line = readline()) { lines = line.split(' '); if (index > m.length - 1) { index = 0; m = m2; } lines.forEach((item, idx) => { m[index][idx] = item; }); index++; } // 求两个矩阵相乘的结果 m1.forEach((item, index) => { for (let i = 0; i < m2y; i++) { let arrY = m2.map(it => it[i]); res[index][i] = getItemSum(item, arrY); } }); res.forEach(item => { print(item.join(' ')); })