Home > Mobile >  Problem with algorithm calculating the determinant of N x N square matrix
Problem with algorithm calculating the determinant of N x N square matrix

Time:12-22

I have an algorithm which should calculate the determinant of square matrix. But there are some strange things happening with the algorithm. The problem is described in the code. This is my first question on this site so don't bite.

function determinant(m) {
  // if the matrix is 1 x 1 then the determinant is inner element of the matrix
  if (m.length === 1) {
    return m[0][0];
  }
  let det = 0;

  // the loop for every element of the first row of the matrix
  for (let i = 0; i < m[0].length; i  ) {

    // matrix is changed after first iteration!?! but it shouldn't
    console.log(`m array on ${i} interation:    `   m.join(""))

    // copy of matrix
    let temp = [...m];

    // deleting the first row of the matrix
    let num = temp.shift()[i];

    // cutting down column's elements of the same index
    for (let k = 0; k < temp.length; k  ) {
      temp[k].splice(i, 1);
    }

    // calculating the determinant
    det  = num * ((-1) ** (1   i   1)) * determinant(temp);
  }

  return det;
};

console.log(determinant([
  [5, 1],
  [5, 6]
]));

CodePudding user response:

The problem stems from your use of the spread operator. You use it correctly, but the internal arrays are still references to the original array objects.

You can see here that the array a is the same object as d[0]. So when you change d[0] you are also changing a by reference.

const a = [1,2]
const b = [3,4]
const d = [a, b]
const e = [...d]

console.log(Object.is(e[0],a))

The solution is to change .splice() to slice in the following example:

const a = [1,2]
const b = [3,4]
const d = [a, b]

const e = [...d]

console.log(Object.is(e[0],a))

e[1] = e[1].slice(0,1);

console.log(d)
console.log(e)

CodePudding user response:

You can try this. based on recursive Algorithm. it will be shorter and easier

const determinant = m => 
  m.length == 1 ?
  m[0][0] :
  m.length == 2 ? 
  m[0][0]*m[1][1]-m[0][1]*m[1][0] :
  m[0].reduce((r,e,i) => 
    r (-1)**(i 2)*e*determinant(m.slice(1).map(c => 
      c.filter((_,j) => i != j))),0)

const test1 = [[3]]                      // 3
const test2 = [[3,-2],[7,4]]             // 26
const test3 = [[1,3,7],[2,-1,4],[5,0,2]] // 81

console.log(determinant(test1))
console.log(determinant(test2))
console.log(determinant(test3))

<!-- begin snippet: js hide: false console: true babel: false -->

  • Related