Created
January 29, 2018 08:28
-
-
Save yortuc/b44d70a959daf67ca2b850be7359c734 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const transpose = (m) => { | |
return m[0].reduce((acc, _, colIndex) => | |
[...acc, m.map(row => row[colIndex])], | |
[]); | |
} | |
const multiplyOneRow = (row1, m2T) => { | |
if(row1.length === 3){ | |
return [ | |
row1[0]*m2T[0][0] + row1[1]*m2T[0][1] + row1[2]*m2T[0][2], | |
row1[0]*m2T[1][0] + row1[1]*m2T[1][1] + row1[2]*m2T[1][2] | |
]; | |
} | |
return [ | |
row1[0]*m2T[0][0] + row1[1]*m2T[0][1], | |
row1[0]*m2T[1][0] + row1[1]*m2T[1][1] | |
]; | |
} | |
const multiply = (m1, m2) => { | |
const m2T = transpose(m2); | |
return m1.map(row=>multiplyOneRow(row, m2T)); | |
} | |
it('transpose nxn matrix', function() { | |
const m1 = [ | |
[1,2,3], | |
[4,5,6] | |
]; | |
const transposedM1 = [ | |
[1,4], | |
[2,5], | |
[3,6] | |
]; | |
assert.deepEqual(transpose(m1), transposedM1); | |
}); | |
it('multiply 1x2 matrix with 2x2', ()=> { | |
const m1 = [ | |
[1, 2] | |
]; | |
const m2 = [ | |
[3, 4], | |
[5, 6] | |
]; | |
const expected = [ | |
[13, 16] | |
] | |
assert.deepEqual(multiply(m1, m2), expected); | |
}); | |
it('multiply 3x2 matrix with 2x2', ()=> { | |
const m1 = [ | |
[1, 2], | |
[3, 4], | |
[5, 6] | |
]; | |
const m2 = [ | |
[7, 8], | |
[9, 10] | |
]; | |
const expected = [ | |
[25, 28], | |
[57, 64], | |
[89, 100] | |
] | |
assert.deepEqual(multiply(m1, m2), expected); | |
}); | |
it('multiply 2x3 matrix with 3x2', ()=> { | |
const m1 = [ | |
[1, 2, 3], | |
[4, 5, 6] | |
]; | |
const m2 = [ | |
[7, 8], | |
[9, 10], | |
[11, 12] | |
]; | |
const expected = [ | |
[58, 64], | |
[139, 154] | |
]; | |
assert.deepEqual(multiply(m1, m2), expected); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment