html
html
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
<!DOCTYPE html>
<html>
<!--
------Seen on CodeWars------
Write a function that accepts a square matrix (n x n 2D array) and returns the determinant of the matrix.
How to take the determinant of a matrix -- it is simplest to start with the smallest cases: A 1x1 matrix |a| has determinant a. A 2x2 matrix [[a, b], [c, d]] or
|a b|
|c d|
has determinant ad - bc.
The determinant of an n x n sized matrix is calculated by reducing the problem to the calculation of the determinants of n n-1 x n-1 matrices. For the 3x3 case, [[a, b, c], [d, e, f], [g, h, i]] or
|a b c|
|d e f|
|g h i|
the determinant is: a * det(a_minor) - b * det(b_minor) + c * det(c_minor) where det(a_minor) refers to taking the determinant of the 2x2 matrix created by crossing out the row and column in which the element a occurs, or
|e f|
|h i|
Note the alternation of signs.
Enter to Rename, Shift+Enter to Preview
css
css
1
2
3
body {
}
Enter to Rename, Shift+Enter to Preview
js
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
function determinant(m) {
if (m.length==1) {
if (typeof m[0] === 'object' ){
return m[0][0];
} else {
return m[0];
}
}
var minors = [];
for (var i = 0; i < m[0].length; i += 1) {
minors[i] = [];
for (var j = 0; j < m[0].length; j += 1) {
if (j==0) continue;
if (!minors[i][j-1]) minors[i][j-1] = [];
for (var k = 0; k < m[0].length; k += 1 ) {
if (k==i) continue;
minors[i][j-1].push(m[j][k]);
}
}
}
var multiplier = 1;
var subResults = [];
for (var i = 0; i < m.length; i += 1 ) {
subResults[i] = multiplier * m[0][i] * determinant(minors[i]);
multiplier *= -1;
}
return subResults.reduce( function( sum, val ) {return sum + val; }, 0 );
Enter to Rename, Shift+Enter to Preview
BROWSER
Console
Run