forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeterminant.js
More file actions
Latest commit
78 lines (75 loc) · 1.82 KB
/
Copy pathDeterminant.js
File metadata and controls
78 lines (75 loc) · 1.82 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* Given a square matrix, find its determinant using Laplace Expansion.
* Time Complexity : O(n!)
*
* For more info: https://en.wikipedia.org/wiki/Determinant
*
* @param {number[[]]} matrix - Two dimensional array of integers.
* @returns {number} - An integer equal to the determinant.
*
* @example
* const squareMatrix = [
* [2,3,4,6],
* [5,8,9,0],
* [7,4,3,9],
* [4,0,2,1]
* ];
*
* const result = determinant(squareMatrix);
* // The function should return 858 as the resultant determinant.
*/
constsubMatrix=(matrix,i,j)=>{
letmatrixSize=matrix[0].length
if(matrixSize===1){
returnmatrix[0][0]
}
letsubMatrix=[]
for(letx=0;x<matrixSize;x++){
if(x===i){
continue
}
subMatrix.push([])
for(lety=0;y<matrixSize;y++){
if(y===j){
continue
}
subMatrix[subMatrix.length-1].push(matrix[x][y])
}
}
returnsubMatrix
}
constisMatrixSquare=(matrix)=>{
letnumRows=matrix.length
for(leti=0;i<numRows;i++){
if(numRows!==matrix[i].length){
returnfalse
}
}
returntrue
}
constdeterminant=(matrix)=>{
if(
!Array.isArray(matrix)||
matrix.length===0||
!Array.isArray(matrix[0])
){
thrownewError('Input is not a valid 2D matrix.')
}
if(!isMatrixSquare(matrix)){
thrownewError('Square matrix is required.')
}
letnumCols=matrix[0].length
if(numCols===1){
returnmatrix[0][0]
}
letresult=0
letsetIndex=0
for(leti=0;i<numCols;i++){
result+=
Math.pow(-1,i)*
matrix[setIndex][i]*
determinant(subMatrix(matrix,setIndex,i))
}
returnresult
}
export{determinant}