0

I have the following Code for forming matrix and finding its determinant :-

function matrix(m, n, arr) {
  var result = {};
  for (t = 1; t <= m; t++) {
    result[t] = {};
  }
  for (i = 1; i <= m; i++)
    for (j = 1; j <= n; j++) result[i][j] = arr[n * (i - 1) + j - 1];
  return { result: result, m: m, n: n };
}
function det(mat) {
  if (mat.m == mat.n) {
    if (mat.m != 1) {
      var k = mat.m;
      var result = 0;
      var temp = [];
      for (i = 1; i <= k; i++) {
        result +=
          (-1) ** (1 + i) *
          mat.result[1][i] *
          function() {
            for (t = 1; t <= k; t++) {
              for (p = 1; p <= k; p++) {
                if (t != 1 || p != i) {
                  temp.push(mat.result[t][p]);
                }
                return det(matrix(k - 1, k - 1, temp));
              }
            }
          };
      }
    } else {
      return mat.result[1][1];
    }
    return result;
  } else {
    return;
  }
}

On performing function like det(matrix(2,2,[2,3,1,4])) it returns NaN.
Please help me resolve the unexpected result.

lloydaf
  • 605
  • 3
  • 17

1 Answers1

1

You're multiplying a value by a function object:

result +=
  (-1) ** (1 + i) *
  mat.result[1][i] *                              // Here
  function() {                                    // ..
    for (t = 1; t <= k; t++) {
      for (p = 1; p <= k; p++) {
        if (t != 1 || p != i) {
          temp.push(mat.result[t][p]);
        }
        return det(matrix(k - 1, k - 1, temp));
      }
    }
  };                                               // Note no () calling it

Treating a function object like a number results in NaN:

var a = 1 * function() { };
console.log(a);

Perhaps you meant to call it (by putting () on the end). It's not clear why you'd need to define it inline like that.


Side note: Your code is falling prey to what I call The Horror of Implicit Globals. You need to declare your variables, in the innermost scope where you need them. I don't see declarations for t, i, j, p... Strongly recommend using strict mode so that shows up as an error.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875