-
Notifications
You must be signed in to change notification settings - Fork 8
/
FormingMagicSquare.cpp
118 lines (105 loc) · 2.33 KB
/
FormingMagicSquare.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int i,j;
int mat[10][10];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cin>>mat[i][j];
}
}
int sum=0;
int a1=0,a2=0,a3=0,a4=0,a5=0,a6=0,a7=0,a8=0;
//The 8 possible Matrices
int m1[3][3]={
{8,3,4},{1,5,9},{6,7,2}
};
int m2[3][3]={
{8,1,6},{3,5,7},{4,9,2}
};
int m3[3][3]={
{6,7,2},{1,5,9},{8,3,4}
};
int m4[3][3]={
{4,9,2},{3,5,7},{8,1,6}
};
int m5[3][3]={
{6,1,8},{7,5,3},{2,9,4}
};
int m6[3][3]={
{4,3,8},{9,5,1},{2,7,6}
};
int m7[3][3]={
{2,7,6},{9,5,1},{4,3,8}
};
int m8[3][3]={
{2,9,4},{7,5,3},{6,1,8}
};
//Calculating the amount required for conversion to each
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a1+=abs(mat[i][j]-m1[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a2+=abs(mat[i][j]-m2[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a3+=abs(mat[i][j]-m3[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a4+=abs(mat[i][j]-m4[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a5+=abs(mat[i][j]-m5[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a6+=abs(mat[i][j]-m6[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a7+=abs(mat[i][j]-m7[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a8+=abs(mat[i][j]-m8[i][j]);
}
}
//Taking the minimum of such amounts
int t1 = min(a1,min(a2,a3));
int t2 = min(a4,min(a5,a6));
int t3 = min(a7,a8);
sum = min(t1,min(t2,t3));
cout<<sum;
}