Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 13a5d57

Browse files
committed
feat: add determinant calculating algorithm
1 parent 1de5ab7 commit 13a5d57

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

Maths/Determinant.js

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/**
2+
* Given a square matrix, find its determinant.
3+
*
4+
* @param {number[[]]} matrix - Two dimensional array of integers.
5+
* @returns {number} - An integer equal to the determinant.
6+
*
7+
* @example
8+
* const squareMatrix = [
9+
* [2,3,4,6],
10+
* [5,8,9,0],
11+
* [7,4,3,9],
12+
* [4,0,2,1]
13+
* ];
14+
*
15+
* const result = determinant(squareMatrix);
16+
* // The function should return 858 as the resultant determinant.
17+
*/
18+
19+
const subMatrix = (matrix, i, j) => {
20+
let matrixSize = matrix[0].length
21+
if (matrixSize === 1) {
22+
return matrix[0][0]
23+
}
24+
let subMatrix = []
25+
for (let x = 0; x < matrixSize; x++) {
26+
if (x === i) {
27+
continue
28+
} else {
29+
subMatrix.push([])
30+
for (let y = 0; y < matrixSize; y++) {
31+
if (y === j) {
32+
continue
33+
} else {
34+
subMatrix[subMatrix.length - 1].push(matrix[x][y])
35+
}
36+
}
37+
}
38+
}
39+
return subMatrix
40+
}
41+
42+
const isMatrixSquare = (matrix) => {
43+
let numRows = matrix.length
44+
for (let i = 0; i < numRows; i++) {
45+
if (numRows !== matrix[i].length) {
46+
return false
47+
}
48+
}
49+
return true
50+
}
51+
52+
const determinant = (matrix) => {
53+
if (
54+
!Array.isArray(matrix) ||
55+
matrix.length === 0 ||
56+
!Array.isArray(matrix[0])
57+
) {
58+
return 'Input is not a valid 2D matrix.'
59+
}
60+
if (isMatrixSquare(matrix) === false) {
61+
return 'Square matrix is required.'
62+
}
63+
let numCols = matrix[0].length
64+
if (numCols === 1) {
65+
return matrix[0][0]
66+
}
67+
let result = null
68+
let setIndex = 0
69+
for (let i = 0; i < numCols; i++) {
70+
result +=
71+
Math.pow(-1, i) *
72+
matrix[setIndex][i] *
73+
determinant(subMatrix(matrix, setIndex, i))
74+
}
75+
return result
76+
}
77+
export { determinant }

0 commit comments

Comments
 (0)