LoginSignup
0

More than 3 years have passed since last update.

JavaScriptで正方行列の行列式を計算する

Posted at

以下の行列Aがある時、

A = 
\begin{matrix}
a & b & c\\ 
d & e & f\\
g & h & i
\end{matrix}

行列式はこう計算出来る。

\begin{vmatrix}
A
\end{vmatrix}
=
\begin{vmatrix}
a & b & c\\ 
d & e & f\\
g & h & i
\end{vmatrix}
=
a\times
\begin{vmatrix}
e & f\\
h & i
\end{vmatrix}
- b\times
\begin{vmatrix}
d & f\\
g & i
\end{vmatrix}
+ c\times
\begin{vmatrix}
d & e\\
g & h
\end{vmatrix}

JavaScriptで実装してみるとこうなった。

function determinant(m) {
  if(m.length === 0) return 1;
  let x = 0;
  for(let ic = 0; ic < m[0].length; ic++) {
    let ans = m.slice(1).map(row => row.filter((_, index) => index !== ic));
    x += ((-1) ** ic) * m[0][ic] * determinant(ans);
  }
  return x;
};

for文をもっと宣言的に書けそう。。。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0