Forming a Magic Square HackerRank Solution in C, C++, Java, Python

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 .

Sample Input 0

4 9 2
3 5 7
8 1 5

Sample Output 0

1


Forming a Magic Square HackerRank Solution in C

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>

int main() {
    int n = 3;
    int a[3][3] = {4,9,2,3,5,7,8,1,6}; 
    int b[3][3];
    int cost = INT_MAX;
    for(int i=0;i<3;i++) {
        for(int j=0;j<3;j++) {
            scanf("%i", &b[i][j]);
        }
    }
    for(int k=0; k<4; k++) {
        int diff1 = 0, diff2 = 0;
        for(int i=0;i<n;i++) {
            for(int j=0;j<n;j++) {
                diff1 += abs(a[i][j]-b[i][j]);
                diff2 += abs(a[i][n-1-j]-b[i][j]);
            }
        }
        if(diff1<cost)
            cost = diff1;
        if(diff2<cost)
            cost = diff2;
        
        for(int i=0; i<n/2; i++) {
            for(int j=0; j<(n+1)/2; j++) {
                int temp = b[i][j];
                b[i][j] = b[n-1-j][i];
                b[n-1-j][i] = b[n-1-i][n-1-j];
                b[n-1-i][n-1-j] = b[j][n-1-i];
                b[j][n-1-i] = temp;
            }
        }
    }
    printf("%i", cost);
    return 0;
}

Forming a Magic Square HackerRank Solution in C++

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    vector<vector<int>> valid_squares = {{8,1,6,3,5,7,4,9,2}, {4,3,8,9,5,1,2,7,6}, {2,9,4,7,5,3,6,1,8},{6,7,2,1,5,9,8,3,4},{6,1,8,7,5,3,2,9,4},{8,3,4,1,5,9,6,7,2},{4,9,2,3,5,7,8,1,6},{2,7,6,9,5,1,4,3,8}};
    int a[9];
    for(int i=0;i<9;i++) cin>>a[i];
    int best = 1000000;
    for(int i=0;i<8;i++){
        int diff = 0;
        for(int j=0;j<9;j++) diff += abs(a[j]-valid_squares[i][j]);
        if (diff<best) best = diff;
    }
    cout<<best<<endl;
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    return 0;
}

Forming a Magic Square HackerRank Solution in Java

import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] a1 = {4, 9, 2, 3, 5, 7, 8, 1, 6};
        int[] a2 = {2, 9, 4, 7, 5, 3, 6, 1, 8};
        int[] a3 = {6, 1, 8, 7, 5, 3, 2, 9, 4};
        int[] a4 = {8, 3, 4, 1, 5, 9, 6, 7, 2};
        int[] a5 = {2, 7, 6, 9, 5, 1, 4, 3, 8};
        int[] a6 = {6, 7, 2, 1, 5, 9, 8, 3, 4};
        int[] a7 = {8, 1, 6, 3, 5, 7, 4, 9, 2};
        int[] a8 = {4, 3, 8, 9, 5, 1, 2, 7, 6};
        int result = 0, c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0, c6 = 0, c7 = 0, c8 = 0;
        for (int i = 0; i < 9; i++){
            int current = scanner.nextInt();
            c1 += (int) Math.abs(current-a1[i]);
            c2 += (int) Math.abs(current-a2[i]);
            c3 += (int) Math.abs(current-a3[i]);
            c4 += (int) Math.abs(current-a4[i]);
            c5 += (int) Math.abs(current-a5[i]);
            c6 += (int) Math.abs(current-a6[i]);
            c7 += (int) Math.abs(current-a7[i]);
            c8 += (int) Math.abs(current-a8[i]);
        }
        List<Integer> list = new ArrayList<>();
            list.add(c1);
            list.add(c2);
            list.add(c3);
            list.add(c4);
            list.add(c5);
            list.add(c6);
            list.add(c7);
            list.add(c8);
        Collections.sort(list);
        System.out.print(list.get(0));
    }
}

Forming a Magic Square HackerRank Solution in Python

import itertools

n1,n2,n3 = map(int, raw_input().strip().split(' '))
n4,n5,n6 = map(int, raw_input().strip().split(' '))
n7,n8,n9 = map(int, raw_input().strip().split(' '))

l = [n1,n2,n3,n4,n5,n6,n7,n8,n9]
tests = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]
def im(l):
    sums = [l[i[0]] + l[i[1]] + l[i[2]] for i in tests]
    return len(set(sums)) == 1

squares = [(2, 7, 6, 9, 5, 1, 4, 3, 8),
(2, 9, 4, 7, 5, 3, 6, 1, 8),
(4, 3, 8, 9, 5, 1, 2, 7, 6),
(4, 9, 2, 3, 5, 7, 8, 1, 6),
(6, 1, 8, 7, 5, 3, 2, 9, 4),
(6, 7, 2, 1, 5, 9, 8, 3, 4),
(8, 1, 6, 3, 5, 7, 4, 9, 2),
(8, 3, 4, 1, 5, 9, 6, 7, 2)]
r = []
for i in squares:
    if im(i):
        cost = sum([abs(l[j] - i[j]) for j in range(9)])
        r.append(cost)
print min(r)

 

Attempt Forming a Magic Square HackerRank Challenge

Link – https://www.hackerrank.com/challenges/magic-square-forming

Next HackerRank Challenge Solution 

Link – https://exploringbits.com/picking-numbers-hackerrank-solution/

Leave a Comment