In mathematics, a determinant is a special number that you can calculate for square matrices. It’s special because it is only nonzero if and only if the matrix is invertible and the linear map represented by the matrix is an isomorphism.
That’s a lot of big words don’t you think?
For today’s problem, we don’t need to understand what determinants are used for, just how to calculate them. If you are interested you can read more about them on the Wikipedia page and here is an amazing page that shows you how to calculate them.
The task is to determine the determinant of any square matrix programmatically. The good news is that it’s pretty easy for 2×2 matrices. You take the difference of the product of each diagonal.
Example
[1 2]
[3 4]
determinant = 1*4 - 2*3
The bad news is that for matrices larger than 2×2 there is no handy calculation. You have to break the larger ones into 2×2 by choosing a row or column. Then multiply that value by the determinant for the matrix that results if you exclude that row and each element of that column. So for example;
[a b c]
[d e f]
[g h i]
determinant = a(ei − fh) − b(di − fg) + c(dh − eg)
Or
[a b c]
[d e f]
[g h i]
determinant = a(ei − fh) − e(bi − ch) + h(bf − ec)
Regardless of going by row or column, you will get the same value. The proof is beyond the scope of this post so just trust me.
If you are still confused I recommend this page they do a much better job of explaining than I do.
Determinant Code
So how do we solve this in javascript? The same way we do it by hand. We break the large matrices until we have 2×2 matrices.
Classic recursion.
Also worth pointing out that the determinant for a 1×1 matrix is the value itself.
const determinant = (matrix) => {
if (matrix.length === 1) {
return matrix[0][0]
}
if (matrix[0].length === 2) {
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
}
const getSubMatrix = (parent, x, y) => {
parent.splice(x, 1)
parent.map(x => x.splice(y, 1))
return parent
}
let det = 0
for (let i = 0; i < matrix[0].length; i++) {
const workArray = JSON.parse(JSON.stringify(matrix))
const subArray = getSubMatrix(workArray, i, 0)
if (i % 2 === 0) {
det += matrix[i][0] * determinant(subArray)
} else {
det -= matrix[i][0] * determinant(subArray)
}
}
return det
}
Code language: JavaScript (javascript)
This is one of the longer codes I’ve put on this site so you may want to play around with it. Send me your thoughts on Twitter, @phoexer, and as always happy coding.