-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy path21Problem.js
75 lines (61 loc) · 1.68 KB
/
21Problem.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
function addMatrices(matrixOne, matrixTwo) {
if (
matrixOne.length !== matrixTwo.length ||
matrixOne[0].length !== matrixTwo[0].length
) {
return "Matrix dimensions are not compatible for addition.";
}
const result = [];
for (let i = 0; i < matrixOne.length; i++) {
result[i] = [];
for (let j = 0; j < matrixOne[i].length; j++) {
result[i][j] = matrixOne[i][j] + matrixTwo[i][j];
}
}
return result;
}
function subtractMatrices(matrixOne, matrixTwo) {
if (
matrixOne.length !== matrixTwo.length ||
matrixOne[0].length !== matrixTwo[0].length
) {
return "Matrix dimensions are not compatible for subtraction.";
}
const result = [];
for (let i = 0; i < matrixOne.length; i++) {
result[i] = [];
for (let j = 0; j < matrixOne[i].length; j++) {
result[i][j] = matrixOne[i][j] - matrixTwo[i][j];
}
}
return result;
}
function multiplyMatrices(matrixOne, matrixTwo) {
if (matrixOne[0].length !== matrixTwo.length) {
return "Matrix dimensions are not compatible for multiplication.";
}
const result = [];
for (let i = 0; i < matrixOne.length; i++) {
result[i] = [];
for (let j = 0; j < matrixTwo[0].length; j++) {
let sum = 0;
for (let k = 0; k < matrixOne[0].length; k++) {
sum += matrixOne[i][k] * matrixTwo[k][j];
}
result[i][j] = sum;
}
}
return result;
}
// Example usage:
const matrixA = [
[1, 2],
[3, 4],
];
const matrixB = [
[5, 6],
[7, 8],
];
console.log("Matrix Addition:", addMatrices(matrixA, matrixB));
console.log("Matrix Subtraction:", subtractMatrices(matrixA, matrixB));
console.log("Matrix Multiplication:", multiplyMatrices(matrixA, matrixB));