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
Jim and the Skyscrapers
Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space
View Solution →Palindromic Subsets
Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t
View Solution →Counting On a Tree
Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n
View Solution →Polynomial Division
Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie
View Solution →Costly Intervals
Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the
View Solution →The Strange Function
One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting
View Solution →