**Forming a Magic Square**

### Problem Statement :

We define a magic square to be an n * n matrix of distinct positive integers from 1 to n^2 where the sum of any row, column, or diagonal of length n is always equal to the same number: the magic constant. You will be given a 3 * 3 matrix s of integers in the inclusive range [1, 9]. We can convert any digit a to any other digit b in the range [1, 9] at cost of | a - b |. Given s, 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 [1, 9]. 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 |5 - 8| + |8 - 9| + |4 - 7| = 7. Function Description Complete the formingMagicSquare function in the editor below. formingMagicSquare has the following parameter(s): int s[3][3]: a 3 * 3 array of integers Returns int: the minimal total cost of converting the input square to a magic square Input Format Each of the 3 lines contains three space-separated integers of row s[i]. Constraints s[i][j] belongs to [1, 9]

### Solution :

` ````
Solution in C :
python 3 :
import itertools
s = []
for i in range(3):
s.extend(list(map(int, input().split(" "))))
min_cost = 1000
best = None
def is_magic(s):
for i in range(3):
if sum(s[i*3:i*3+3]) != 15:
return False
if sum(s[i::3]) != 15:
return False
if s[0] + s[4] + s[8] != 15:
return False
if s[2] + s[4] + s[6] != 15:
return False
return True
best = None
for p in itertools.permutations(range(1,10)):
cost = sum([abs(p[i] - s[i]) for i in range(len(s))])
if cost < min_cost and is_magic(p):
min_cost = cost
best = p
print(min_cost)
Java :
import java.io.*;
import java.util.*;
public class crap {
public static int diff(int[][] s1,int[][] s2){
int d=0;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
d+=Math.abs(s1[i][j]-s2[i][j]);
return d;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int s[][]=new int[3][3];
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{s[i][j]=sc.nextInt();}
int a[][]={{2,7,6},{9,5,1},{4,3,8}};
int b[][]={{2,9,4},{7,5,3},{6,1,8}};
int c[][]={{4,3,8},{9,5,1},{2,7,6}};
int d[][]={{4,9,2},{3,5,7},{8,1,6}};
int e[][]={{6,1,8},{7,5,3},{2,9,4}};
int f[][]={{6,7,2},{1,5,9},{8,3,4}};
int g[][]={{8,1,6},{3,5,7},{4,9,2}};
int h[][]={{8,3,4},{1,5,9},{6,7,2}};
ArrayList<int[][]> val=new ArrayList<>();
int res=Integer.MAX_VALUE;
val.add(a);val.add(b);val.add(c);val.add(d);val.add(e);val.add(f);val.add(g);val.add(h);
for(int[][] x:val){
res=Math.min(res, diff(x, s));
}
System.out.println(res);
}
}
C++ :
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int arr[9] = {4,9,2,3,5,7,8,1,6} ;
int arr1[9] = {2,7,6,9,5,1,4,3,8} ;
int arr2[9] = {6,1,8,7,5,3,2,9,4};
int arr3[9] = {2,9,4,7,5,3,6,1,8};
int arr4[9] = {6,7,2,1,5,9,8,3,4};
int arr5[9] = {8,1,6,3,5,7,4,9,2};
int arr6[9] = {8,3,4,1,5,9,6,7,2};
int arr7[9] = {4,3,8,9,5,1,2,7,6};
int ans[8] = {0};
for(int i =0;i<9;i++)
{
int k;cin>>k;
ans[0] += abs(k - arr[i]);
ans[1] += abs(k - arr1[i]);
ans[2] += abs(k - arr2[i]);
ans[3] += abs(k - arr3[i]);
ans[4] += abs(k - arr4[i]);
ans[5] += abs(k - arr5[i]);
ans[7] += abs(k - arr7[i]);
ans[6] += abs(k - arr6[i]);
}
int min =ans[0];
for(int i=0;i<8;i++)
if(ans[i]<min)
min = ans[i];
cout<<min<<endl;
return 0;
}
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;
}
```

## View More Similar Problems

## QHEAP1

This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →## Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →## Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →## Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →## Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →## Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →