• + 0 comments

    My Javascript Solution:

    function formingMagicSquare(s) {
        let possible_a_b = [
            [-3,-1],
            [-3,1],
            [-1,-3],
            [-1,3],
            [1,-3],
            [1,3],
            [3,-1],
            [3,1]
        ]
        let costs = [0,0,0,0,0,0,0,0]
        for (let i = 0; i < possible_a_b.length; i++) {
            let [a,b] = possible_a_b[i];
            let magicSquare = [
                [5-b, 5+(a+b), 5 -a],
                [5-(a-b), 5, 5+(a-b)],
                [5+a, 5-(a+b), 5+b]
            ]
            for (let j = 0; j < s.length; j++) {
                for (let k = 0; k < s[j].length; k++) {
                    if (s[j][k] !== magicSquare[j][k]) {
                        costs[i] = costs[i] + Math.abs(s[j][k] - magicSquare[j][k])
                    }
                }
            }
        }
        costs.sort((a,b) => a -b)
        return costs[0]
    

    }