Forming a Magic Square HackerRank Solution

In this Forming a Magic Square HackerRank solution, We define a magic square to be an  matrix of distinct positive integers from  to  where the sum of any row, column, or diagonal of length  is always equal to the same number: the magic constant.

You will be given a  matrix  of integers in the inclusive range . We can convert any digit  to any other digit  in the range  at cost of . Given , convert it into a magic square at minimal cost. Print this cost on a new line.

Note: The resulting magic square must contain distinct integers in the inclusive range .

Example

$s = [[5, 3, 4], [1, 5, 8], [6, 4, 2]]

The matrix looks like this:

5 3 4
1 5 8
6 4 2

We can convert it to the following magic square:

8 3 4
1 5 9
6 7 2

This took three replacements at a cost of .

Function Description

Complete the formingMagicSquare function in the editor below.

formingMagicSquare has the following parameter(s):

  • int s[3][3]: a  array of integers

Returns

  • int: the minimal total cost of converting the input square to a magic square

Input Format

Each of the  lines contains three space-separated integers of row .

Constraints

Sample Input

4 9 2
3 5 7
8 1 5

Sample Output

1

Explanation

Matrix  initially looks like this:

4 9 2
3 5 7
8 1 5

Observe that it’s not yet magic, because not all rows, columns, and center diagonals sum to the same number.

If we change the bottom right value, , from  to  at a cost of ,  becomes a magic square at the minimum possible cost. Thus, we print the cost, , on a new line.

Forming a Magic Square HackerRank Solution

I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.

Problem Solution in C++

int formingMagicSquare(vector<vector<int>> s) {
    vector<vector<int>> Square{
        {8,3,4,1,5,9,6,7,2},
        {4,3,8,9,5,1,2,7,6},
        {8,1,6,3,5,7,4,9,2},
        {6,1,8,7,5,3,2,9,4},
        {2,9,4,7,5,3,6,1,8},
        {4,9,2,3,5,7,8,1,6},
        {2,7,6,9,5,1,4,3,8},
        {6,7,2,1,5,9,8,3,4}
    };
    // int len = Square[0].size();
    // cout<<"The size is : "<<len<<endl;
        int min = INT_MAX;
    // cout<<"The value of INTMAX is : "<<min<<endl;
    for (int i = 0; i < Square.size(); i++) {
        int total = 0;
        for (int j = 0; j < Square[i].size(); j++) {
            // cout<<"The value of s["<<j/3<<"]["<<j%3<<"] is "<<s[j/3][j%3]<<endl;
            total = total + abs(Square[i][j] - s[j/3][j%3]);
        }
        // cout<<"The value of total is : "<<total<<endl;
        if (total < min) {
            min = total;
        }
    }
    return min;
}

Problem Solution in Python

def formingMagicSquare(s):
    magic_squares = [
    [[8, 1, 6], [3, 5, 7], [4, 9, 2]],
    [[6, 1, 8], [7, 5, 3], [2, 9, 4]],
    [[4, 9, 2], [3, 5, 7], [8, 1, 6]],
    [[2, 9, 4], [7, 5, 3], [6, 1, 8]],
    [[8, 3, 4], [1, 5, 9], [6, 7, 2]],
    [[4, 3, 8], [9, 5, 1], [2, 7, 6]],
    [[6, 7, 2], [1, 5, 9], [8, 3, 4]],
    [[2, 7, 6], [9, 5, 1], [4, 3, 8]]
    ]
    min_moves = float('inf')
    for magic_square in magic_squares:
        moves = 0
        for i in range(3):
            for j in range(3):
                moves += abs(s[i][j] - magic_square[i][j])
        if moves < min_moves:
            min_moves = moves
    return min_moves

Problem Solution in C#

public static int FormingMagicSquare(List<List<int>> s)
        {
            List<List<int>> magic = new List<List<int>> {
                new List<int> {8, 1, 6, 3, 5, 7, 4, 9, 2},
                new List<int> {6, 1, 8, 7, 5, 3, 2, 9, 4},
                new List<int> {4, 9, 2, 3, 5, 7, 8, 1, 6},
                new List<int> {2, 9, 4, 7, 5, 3, 6, 1, 8},
                new List<int> {8, 3, 4, 1, 5, 9, 6, 7, 2},
                new List<int> {4, 3, 8, 9, 5, 1, 2, 7, 6},
                new List<int> {2, 7, 6, 9, 5, 1, 4, 3, 8},
                new List<int> {6, 7, 2, 1, 5, 9, 8, 3, 4}};



            List<int> flatList = new List<int>();
            foreach (var oneList in s)
                foreach (int num in oneList)
                    flatList.Add(num);


            int response = int.MaxValue;


            foreach (var term in magic)
            {
                int temp = getCost(term, flatList);
                if (response > temp)
                    response = temp;
            }
            return response;
        }


        private static int getCost(List<int> magic, List<int> data)
        {
            int sum = 0;
            for (int i = 0; i < data.Count; i++)
                if (data[i] != magic[i])
                    sum += Math.Abs(data[i] - magic[i]);
            return sum;
        }

Problem Solution in JavaScript

function formingMagicSquare(s) {
    const possibleSquares = [
       
        [[8, 1, 6], [3,5,7], [4,9,2]],
        [[6, 1, 8], [7,5,3], [2,9,4]],
       
        [[8, 3, 4], [1,5,9], [6,7,2]],
        [[6, 7, 2], [1,5,9], [8,3,4]],
       
        [[4, 3, 8], [9,5,1], [2,7,6]],
        [[2, 7, 6], [9,5,1], [4,3,8]],
       
        [[4, 9, 2], [3,5,7], [8,1,6]],
        [[2, 9, 4], [7,5,3], [6,1,8]],
       
    ];
   
   
    let minCost = Number.MAX_VALUE;
   
    possibleSquares.forEach(squareMatrix => {
        let cost = 0;
        for(let i = 0; i < 3; i++){
            for(let j = 0; j < 3; j++){
                cost += Math.abs(squareMatrix[i][j] - s[i][j])
            }
        }
        if(cost < minCost){
            minCost = cost;
        }
    })
 
   
    return minCost;
}
Solve original Problem on HackerRank here. Checkout more HackerRank Problems

Leave a Comment