Compress Matrix to a single digit. By Multiplying all the row and adding all the column as follows
Input
[
a1, b1
a2, b2
]
( a1 * a2 ) + (b1 * b2)
Sample
[
[1, 2, 4],
[5, 2, 1],
[4, 5, 1]
]
= ( 1 * 5 * 4 ) + ( 2 * 2 * 5 ) + ( 4 * 1 * 1)
= 20 + 20 + 4
= 44
for empty matric, return 0
function matrixCompress(m) {
let cols = [];
for( const rows of m ) {
for( const colIndex in rows ) {
const el = rows[colIndex];
if( cols[colIndex] === undefined ) {
cols[colIndex] = el;
}
else {
cols[colIndex] = el * cols[colIndex];
}
}
}
return cols.reduce((acc, curr)=>acc+curr, 0);
}
// Since Node 10, we're using Mocha.
// You can use `chai` for assertions.
const chai = require("chai");
const assert = chai.assert;
// Uncomment the following line to disable truncating failure messages for deep equals, do:
// chai.config.truncateThreshold = 0;
// Since Node 12, we no longer include assertions from our deprecated custom test framework by default.
// Uncomment the following to use the old assertions:
// const Test = require("@codewars/test-compat");
describe("Solution", function() {
it("should handle any matrix", function() {
assert.strictEqual(matrixCompress([
[1,2,4],
[5,2,1],
[4,5,1]
]), 44)
assert.strictEqual(matrixCompress([
[8, 9],
[7, 2]
]), 74)
assert.strictEqual(matrixCompress([]), 0)
});
});