SHARE
TWEET

Magic Matrices 100/100 (2 solutions)

AreWe Jun 28th, 2020 (edited) 1,560 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Note: Solution #1 is much much faster in the worst case scenario -> true
  3.  * and MUCH MUCH MUCH FASTER in the best case scenario -> false
  4.  */
  5.  
  6. // Solution #1 - row by row and col by col
  7. magicMatrices1 = (matrix = []) => {
  8.     const N = matrix.length;
  9.  
  10.     let rowSum = matrix[0].reduce((a, b) => a + b, 0);
  11.  
  12.     for(let i = 1; i < N; i++) {
  13.         let currentRowSum = 0;
  14.         for(let j = 0; j < N; j++) {
  15.             currentRowSum += matrix[i][j];
  16.         }
  17.  
  18.         if(currentRowSum !== rowSum) {
  19.             return false;
  20.         }
  21.     }
  22.  
  23.     for(let i = 0; i < N; i++) {
  24.         let colSum = 0;
  25.         for(let j = 0; j < N; j++) {
  26.             colSum += matrix[j][i];
  27.         }
  28.  
  29.         if(colSum !== rowSum) {
  30.             return false;
  31.         }
  32.     }
  33.  
  34.     return true;
  35. };
  36.  
  37. // Solution #2 - all rows and all cols -> then full check sum by sum
  38. magicMatrices2 = (matrix = []) => {
  39.     const N = matrix.length;
  40.  
  41.     const sums = [new Array(N).fill(0), new Array(N).fill(0)];
  42.  
  43.     for(let i = 0; i < N; i++) {
  44.         for(let j = 0; j < N; j++) {
  45.             sums[0][i] += matrix[i][j];
  46.             sums[1][j] += matrix[j][i];
  47.         }
  48.     }
  49.  
  50.     for(let i = 0; i < 2; i++) {
  51.         for(let j = 0; j < N; j++) {
  52.             if(sums[i][j] !== sums[0][0]) {
  53.                 return false;
  54.             }
  55.         }
  56.     }
  57.  
  58.     return true;
  59. };
  60.  
  61. /**
  62.  * true
  63.  * true
  64.  * don't mind me: 46192.823ms
  65.  * true
  66.  * test1: 15805.907ms
  67.  * true
  68.  * test2: 32243.004ms
  69.  */
  70. const N = 15000;
  71. let matrix = new Array(N);
  72. for(let i = 0; i < N; i++) {
  73.     matrix[i] = new Array(N).fill(1);
  74. }
  75. // matrix[0][1] = 0;
  76. // false
  77. // false
  78. // don't mind me: 30526.394ms
  79. // false
  80. // test1: 3.042ms
  81. // false
  82. // test2: 31248.469ms
  83.  
  84.  
  85. console.time('don\'t mind me');
  86. console.log(magicMatrices1(matrix));
  87. console.log(magicMatrices2(matrix));
  88. console.timeEnd('don\'t mind me');
  89.  
  90.  
  91. console.time('test1');
  92. console.log(magicMatrices1(matrix));
  93. console.timeEnd('test1');
  94.  
  95. console.time('test2');
  96. console.log(magicMatrices2(matrix));
  97. console.timeEnd('test2');
  98. //*/
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