Ivankooo1

Magic Matrix

Sep 2nd, 2019
710
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function isMagicMatrix(matrix) {
  2.     let sumRow = row => matrix[row].reduce((a, b) => a + b);
  3.     let sumCol = col => matrix.map(row => row[col])
  4.         .reduce((a, b) => a + b);
  5.  
  6.     if (matrix.length > 0) {
  7.         let targetSum = sumRow(0);
  8.  
  9.         for (let i = 1; i < matrix.length; i++) {
  10.             let rowSum = sumRow(i);
  11.             if (rowSum !== targetSum) {
  12.                 return false;
  13.             }
  14.         }
  15.  
  16.         for (let j = 0; j < matrix[0].length; j++) {
  17.             let colSum = sumCol(j);
  18.             if (colSum !== targetSum) {
  19.                 return false;
  20.             }
  21.         }
  22.     }
  23.  
  24.     return true;
  25. }
  26.  
  27. console.log(isMagicMatrix(
  28.     [[4, 5, 6],
  29.     [6, 5, 4],
  30.     [5, 5, 5]]
  31. ));
Advertisement
Add Comment
Please, Sign In to add comment