Created
October 19, 2021 11:29
-
-
Save Stefanacef/b30ef9046dd07f5115341bb00e0c1413 to your computer and use it in GitHub Desktop.
Solution for "Forming a Magic Square" in Hackerrank
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const magic = [ | |
[8, 1, 6, 3, 5, 7, 4, 9, 2], | |
[6, 1, 8, 7, 5, 3, 2, 9, 4], | |
[4, 3, 8, 9, 5, 1, 2, 7, 6], | |
[2, 7, 6, 9, 5, 1, 4, 3, 8], | |
[2, 9, 4, 7, 5, 3, 6, 1, 8], | |
[4, 9, 2, 3, 5, 7, 8, 1, 6], | |
[6, 7, 2, 1, 5, 9, 8, 3, 4], | |
[8, 3, 4, 1, 5, 9, 6, 7, 2], | |
]; | |
function formingMagicSquare(s) { | |
const arrOneDimension = [].concat(...s); | |
let min = 45; | |
for (let i = 0; i < magic.length; i++) { | |
let sum = 0; | |
for (let j = 0; j < 9; j++) { | |
const difference = Math.abs(magic[i][j] - arrOneDimension[j]); | |
sum += Math.abs(magic[i][j] - arrOneDimension[j]); | |
} | |
if (min > sum) min = sum; | |
} | |
return min; | |
} | |
console.log(formingMagicSquare(s)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment