Created
March 4, 2021 07:57
-
-
Save luillyfe/a4caadc8337ee5d995bc14f853d795d2 to your computer and use it in GitHub Desktop.
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
function formingMagicSquare(s) { | |
const magicSquares = getMagicSquares(3) | |
const distances = getDistances(magicSquares, s) | |
return distances.sort((a,b) => a-b)[0] | |
} | |
function getDistances(magicSquares, square) { | |
return Object.keys(magicSquares).reduce((distances, key) => { | |
distances.push(getDistance(magicSquares[key], square)) | |
return distances | |
}, []) | |
} | |
function getDistance(magicSquare, square) { | |
const length = magicSquare.length; | |
let distance = 0; | |
for (let i=0;i<length;i++) { | |
for (let j=0;j<length;j++) { | |
distance += Math.abs(magicSquare[i][j] - square[i][j]) | |
} | |
} | |
return distance | |
} | |
function getMagicSquares(n) { | |
const evenNumbersPermutations = getAllPermutations([2,4,6,8]) | |
const squares = {} | |
let i=0,j=0, | |
length=evenNumbersPermutations.length, | |
magicK=15; | |
for (let id=0;id<length;id++) { | |
squares[id] = [[], [], []] | |
let A = squares[id], | |
evenNumbers = evenNumbersPermutations[id] | |
A[1][1] = 5 | |
A[i][j] = evenNumbers[0] | |
A[i][j+2] = evenNumbers[1] | |
A[i+2][j] = evenNumbers[2] | |
A[i+2][j+2] = evenNumbers[3] | |
A[i][j+1] = magicK - (A[i][j] + A[i][j+2]) | |
A[i+1][j] = magicK - (A[i][j] + A[i+2][j]) | |
A[i+1][j+2] = magicK - (A[i][j+2] + A[i+2][j+2]) | |
A[i+2][j+1] = magicK - (A[i][j+1] + A[i+1][j+1]) | |
} | |
return Object.keys(squares).reduce(isAMagicSquare, squares) | |
} | |
function isAMagicSquare(squares, key) { | |
const current = squares[key], | |
magicK = 15; | |
if (current[0].reduce((a,b) => a+b) !== magicK || | |
current[1].reduce((a,b) => a+b) !== magicK || | |
current[2].reduce((a,b) => a+b) !== magicK || | |
current[0][0] + current[1][0] + current[2][0] !== magicK || | |
current[0][1] + current[1][1] + current[2][1] !== magicK || | |
current[0][2] + current[1][2] + current[2][2] !== magicK || | |
current[0][0] + current[1][1] + current[2][2] !== magicK) { | |
delete squares[key] | |
} | |
return squares | |
} | |
// from stack overflow, https://stackoverflow.com/a/20871714/2640467 | |
function getAllPermutations(inputArr) { | |
let result = []; | |
const permute = (arr, m = []) => { | |
if (arr.length === 0) { | |
result.push(m) | |
} else { | |
for (let i = 0; i < arr.length; i++) { | |
let curr = arr.slice(); | |
let next = curr.splice(i, 1); | |
permute(curr.slice(), m.concat(next)) | |
} | |
} | |
} | |
permute(inputArr) | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment