SHARE
TWEET

Untitled

a guest May 19th, 2019 77 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Matrix {
  2.   // ...
  3.   determinant() {
  4.     if (this.rows.length !== this.rows[0].length) {
  5.       throw new Error('Only matrices with the same number of rows and columns are supported.')
  6.     }
  7.     if (this.rows.length === 2) {
  8.       return this.rows[0][0] * this.rows[1][1] - this.rows[0][1] * this.rows[1][0]
  9.     }
  10.  
  11.     const parts = this.rows[0].map((coef, index) => {
  12.       const matrixRows = this.rows.slice(1).map(row => [ ...row.slice(0, index), ...row.slice(index + 1)])
  13.       const matrix = new Matrix(...matrixRows)
  14.       const result = coef * matrix.determinant()
  15.       return index % 2 === 0 ? result : -result
  16.     })
  17.  
  18.     return sum(parts)
  19.   }
  20. }
  21.  
  22. const matrix2 = new Matrix(
  23.   [ 0, 3],
  24.   [-2, 1]
  25. )
  26. console.log(matrix2.determinant())
  27. // 6
  28. const matrix3 = new Matrix(
  29.   [2, -3,  1],
  30.   [2,  0, -1],
  31.   [1,  4,  5]
  32. )
  33. console.log(matrix3.determinant())
  34. // 49
  35. const matrix4 = new Matrix(
  36.   [3, 0, 2, -1],
  37.   [1, 2, 0, -2],
  38.   [4, 0, 6, -3],
  39.   [5, 0, 2,  0]
  40. )
  41. console.log(matrix4.determinant())
  42. // 20
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top