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.
[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)
[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.
Also worth pointing out that the determinant for a 1×1 matrix is the value itself.
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.