Search This Blog

2024/04/09

Javascript Algorithm:Matrix Addition

A matrix in arrangement of numbers into rows and columns.In JS a matrix can be
represented with arrays and multi dimensional arrays can be created by nesting
arrays. So in this problem we can use the terms matrices and arrays
interchangeably.
e.g. suppose we want to represent a 2 row 2 column matrix in javascript then
it will look like
let twoDimArr = [
[1,2],
[3, 4]
];

Sum of two matrices:
Fo given two N x M matrices,their sum is again a N x M matrix where each value
in that matrix the sum of values of corresponding elements of the given two
matrices

Sum of Two matrices using by falttening them to one dimesional matrices:
Solution:
let matrixA = [
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4],
];
let matrixB = [
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4],
];
let flattenMatrixA = Array.from(matrixA.flat());
let flattenMatrixB = Array.from(matrixB.flat());

let sumOfFlattenMatrices = flattenMatrixA.map((elem, i) =>
                elem + flattenMatrixB[i]);

let resultMatrix = [];
while (sumOfFlattenMatrices.length) {
resultMatrix.push(sumOfFlattenMatrices.splice(0, matrixA[0].length));
}
console.log(resultMatrix)

Output:
[ [ 2, 2, 2, 2 ], [ 4, 4, 4, 4 ], [ 6, 6, 6, 6 ], [ 8, 8, 8, 8 ] ]


Using Array.map:
Solution:
let matrixA = [
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4],
];
let matrixB = [
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4],
];

let resultMatrix = matrixA.map((matrioxARowElement,rowIndex)=>{
return matrioxARowElement.map((element,colIndex)=>{
return element + matrixB[rowIndex][colIndex]
})
})

console.log(resultMatrix)
Output:
[ [ 2, 2, 2, 2 ], [ 4, 4, 4, 4 ], [ 6, 6, 6, 6 ], [ 8, 8, 8, 8 ] ]


Using Loop:
Solution:
let matrixA = [
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4],
];
let matrixB = [
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4],
];

let result = [];
for (let i = 0; i < matrixA.length; i++) {
let row = [];
for (let j = 0; j < matrixA[0].length; j++) {
row.push(matrixA[i][j] + matrixB[i][j]);
}
result.push(row)
}
console.log(result)
Output:
[ [ 2, 2, 2, 2 ], [ 4, 4, 4, 4 ], [ 6, 6, 6, 6 ], [ 8, 8, 8, 8 ] ]

No comments:

Post a Comment