1
1
/**
2
- * Given a square matrix, find its determinant.
2
+ * Given a square matrix, find its determinant using Laplace Expansion.
3
+ * Time Complexity : O(n!)
3
4
*
4
5
* For more info: https://en.wikipedia.org/wiki/Determinant
5
6
*
@@ -27,15 +28,13 @@ const subMatrix = (matrix, i, j) => {
27
28
for ( let x = 0 ; x < matrixSize ; x ++ ) {
28
29
if ( x === i ) {
29
30
continue
30
- } else {
31
- subMatrix . push ( [ ] )
32
- for ( let y = 0 ; y < matrixSize ; y ++ ) {
33
- if ( y === j ) {
34
- continue
35
- } else {
36
- subMatrix [ subMatrix . length - 1 ] . push ( matrix [ x ] [ y ] )
37
- }
31
+ }
32
+ subMatrix . push ( [ ] )
33
+ for ( let y = 0 ; y < matrixSize ; y ++ ) {
34
+ if ( y === j ) {
35
+ continue
38
36
}
37
+ subMatrix [ subMatrix . length - 1 ] . push ( matrix [ x ] [ y ] )
39
38
}
40
39
}
41
40
return subMatrix
@@ -57,10 +56,10 @@ const determinant = (matrix) => {
57
56
matrix . length === 0 ||
58
57
! Array . isArray ( matrix [ 0 ] )
59
58
) {
60
- return 'Input is not a valid 2D matrix.'
59
+ throw new Error ( 'Input is not a valid 2D matrix.' )
61
60
}
62
- if ( isMatrixSquare ( matrix ) === false ) {
63
- return 'Square matrix is required.'
61
+ if ( ! isMatrixSquare ( matrix ) ) {
62
+ throw new Error ( 'Square matrix is required.' )
64
63
}
65
64
let numCols = matrix [ 0 ] . length
66
65
if ( numCols === 1 ) {
0 commit comments