如何递归实现此行列式求解器代码?

时间:2019-07-09 02:57:40

标签: javascript recursion

我创建了可解决6x6的行列式的代码,但自我 这个问题的相似性使得它看起来非常适合 递归方法。我也想使代码能够解决更大的问题 而不是6x6的矩阵。

我对递归函数的经验很少,所以我不确定 从哪儿开始。我在网上看过一些教程,但大多数只是 关于斐波那契数列或其他一些简单示例。资源会 不胜感激。警告:代码很长。

    function determinant(m) {
      var sum = 0;
      console.log(m);
      if(m.length==1){
        return m[0][0];
      }
      if(m.length==2){
         return twoByTwo(m);
      }
      if(m.length==3){
        return threeByThree(m);
      }
      if(m.length==4){
        return fourByFour(m);
      }
      if(m.length==5){
        return fiveByFive(m);
      }
      if(m.length==6){
        return sixBySix(m);
      }
    }

    ...//5x5 and 6x6 fxns

    //4x4 det fxn
    function fourByFour(m){
      var sum = 0;
      var matrix = JSON.parse(JSON.stringify(m));
      m.shift();
      m[0].shift();
      m[1].shift();
      m[2].shift();
      sum+=(matrix[0][0])*threeByThree(m);
      m = JSON.parse(JSON.stringify(matrix));
      m.shift();
      m[0].splice(1,1);
      m[1].splice(1,1);
      m[2].splice(1,1);
      sum-=(matrix[0][1])*threeByThree(m);
      m = JSON.parse(JSON.stringify(matrix));
      m.shift();
      m[0].splice(2,1);
      m[1].splice(2,1);
      m[2].splice(2,1);
      sum+=(matrix[0][2])*threeByThree(m);
      m = JSON.parse(JSON.stringify(matrix));
      m.shift();
      m[0].pop();
      m[1].pop();
      m[2].pop();
      sum-=(matrix[0][3])*threeByThree(m);
      return sum;
    }
    //3x3 det fxn
    function threeByThree(m){
      var sum = 0;
      var matrix = JSON.parse(JSON.stringify(m));
      m.shift();
      m[0].shift();
      m[1].shift();
      sum+=(matrix[0][0])*twoByTwo(m);
      m = JSON.parse(JSON.stringify(matrix));
      m.shift();
      m[0].splice(1,1);
      m[1].splice(1,1);
      sum-=(matrix[0][1])*twoByTwo(m);
      m = JSON.parse(JSON.stringify(matrix));
      m.shift();
      m[0].pop();
      m[1].pop();
      sum+=(matrix[0][2])*twoByTwo(m);
      return sum;
    }
    //2x2 det fxn
    function twoByTwo(m){
      return ((m[0][0])*(m[1][1])-(m[0][1])*(m[1][0]));
    }

此函数的结果是准确的,但仅适用于最大6x6的矩阵,我想将函数推广为采用任何大小的矩阵。我想可以递归地实现与我目前正在执行的方法类似的方法,然后该函数将能够求解更大矩阵的行列式。

1 个答案:

答案 0 :(得分:1)

通过Wikipedia中提到的“ minor expansion formula”,可以在迭代原始矩阵第一行中的每个索引时,通过计算次要矩阵的行列式来递归计算行列式。

您可以在下面看到一个实现:

function determinant(m) {
  const subMatrix = (index) => m.slice(1).map(row => row.filter((e, colIndex) => colIndex !== index));
  const sign = (index) => index % 2 === 0 ? 1 : -1;

  if (m.length === 1) return m[0][0];
  return m[0].reduce((sum, curr, i) => sum + sign(i) * curr * determinant(subMatrix(i)), 0);
}

const matrix = [
  [1, 2, 3],
  [4, 15, 6],
  [7, 8, 19]
];

console.log(determinant(matrix));

相关问题