window.ENTITIES={'/api/snippets/javascript/javascript%20-%20multiply%20two%20matrixes':[{"result":true,"message":null,"batch":{"type":"javascript","name":"javascript - multiply two matrixes","items":[{"id":"Dd5Knp","type":"javascript","name":"JavaScript - multiply two matrixes","content":"// ONLINE-RUNNER:browser;\n\nconst createMatrix = (width, height, creator = () => 0) => {\n const result = new Array(height);\n for (let y = 0; y < height; ++y) {\n const row = new Array(width);\n for (let x = 0; x < width; ++x) {\n row[x] = creator(x, y);\n }\n result[y] = row;\n }\n return result;\n};\n\nconst findWidth = (matrix) => {\n if (matrix.length > 0) {\n const row = matrix[0];\n if (row) {\n return row.length;\n }\n }\n return 0;\n};\n\nconst findHeight = (matrix) => {\n return matrix.length;\n};\n\nconst multiplyMatrixes = (a, b) => {\n const length = findWidth(a);\n if (length !== findHeight(b)) {\n throw new Error('Matrixes can not be multipled.');\n }\n const width = findWidth(b);\n const height = findHeight(a);\n const result = createMatrix(width, height);\n for (let y = 0; y < height; ++y) {\n const row = result[y];\n for (let x = 0; x < width; ++x) {\n let value = 0;\n for (let i = 0; i < length; ++i) {\n value += a[y][i] * b[i][x];\n }\n row[x] = value;\n }\n }\n return result;\n};\n\n\n// Usage example:\n\nconst a = [\n\t[1, 2],\n\t[4, 5],\n\t[7, 8]\n];\n\nconst b = [\n\t[1, 2, 3],\n\t[4, 5, 6]\n];\n\nconst c = multiplyMatrixes(a, b);\n\nconsole.log(c);\n\n\n// Output:\n//\n// [ 9, 12, 15],\n// [24, 33, 42],\n// [39, 54, 69]","source":"","author":{"id":"xaOmA0","name":"Lily","avatar":"1629130172536__xaOmA0__w40px_h40px.jpg","points":548,"role":"BASIC"},"creationTime":1703112235000,"updateTime":1703116512000,"removalTime":null}]}}]};