settingsAccountsettings
Menusettings

Q: Magic Matrices in JavaScript

+1 vote

Write a JS function that checks if a given matrix of numbers is magical. A matrix is magical if the sums of the cells of every row and every column are equal.

The input comes as an array of arrays, containing numbers (number 2D matrix). The input numbers will always be positive.

Examples:

Input:
[[4, 5, 6],
 [6, 5, 4],
 [5, 5, 5]]

Output:
true


Input:
[[11, 32, 45],
 [21, 0, 1],
 [21, 1, 1]]

Output:
false


Input:
[[1, 0, 0],
 [0, 0, 1],
 [0, 1, 0]]    
 
Output:
true

The output is a Boolean result indicating whether the matrix is magical or not.

asked in JavaScript category by user mm
edited by user golearnweb

1 Answer

0 votes

Here is the solution:

function doMagic(arr) {
    return checkMagic(arr) &&
           checkMagic(rotate(arr));


    function rotate(array) {
        return array[0].map((x, i) => array.map(x => x[i]))
    }
  
    function checkMagic(arr) {
        arr = arr.map(x => x.reduce((a, b) => a + b));

        return Array.from(new Set(arr)).length === 1;
    }
}

 

answered by user golearnweb
...