Solved
Magic Square
Posted on 2004-10-25
Hi, I have a program on magic square. I could check the rows.
To check the coloms and the diagonals it will be done only after all the rows are filled.
If after filling the rows the columns and diagonals are not name number how should I come back and do again.
My program is given below. For some functions the parameters are not fully filled. Take it easy I will do it later on. I want you to guide me how to proceed. More over this is recursive as I have to submit it recursive.
/////////////////////////////////////////Magic square program///////////////////////////////////////////////
#include<stdio.h>
#include<stdlib.h>
#define MAGIC_SQUARE_SUM 15
void permute(int,int,int);
int cal_col_pts(int,int);
int rowsum(int[],int);
int colsum(int[],int,int);
void displayrow(int[],int);
int testmagic(int[],int,int,int);
int A[9],B[9];
void main(void)
{
int n,x=1,num=0,slots=0,point;
printf("Enter a number");
scanf("%d",&n);
printf("Enter the size of the square( 3*3,4*4, 5*5...) ");
scanf("%d",&num);
slots=num*num;
point=cal_col_pts(slots,num);
permute(n,point,num);
}
int cal_col_pts(int slots,int num)
{
int x=slots/num;
x--;
num*=x;
return num+1;
}
void permute(int n,int pts,int num)
{
int i,temp=0;
for (i = 1;i<=9;i++)
{
if( B[i]==0) // if i is free
{
B[i]=1;
A[n]=i;
if ((n % 3) == 0) // if n is div by 3
{
if ( (temp=rowsum(A,i)) == 15 )
{
if( n<9 )
permute(n+1,pts,num);
else // at the end
testmagic(A,i,pts,num);
}
}
else
permute(n+1); //recurse
B[i]=0;
}
}
}
int testmagic(int A[],int i,int pts,int num)
{
int flag1=0,flag2=0,flag3=0;
columnsum(A,max,pts);
diagonalsum();
reverse_diagonaldum();
}
diagonalsum()
{
for(i=0;i<max;i=num+i+1)
{
sum+=A[i];
if(i==pts && (sum!=MAGIC_SQUARE_SUM)
break;
else
continue;
}
}
reverse_diagonal_sum()
{
int sum=0;
for(i=pts;i<=ptsnum;i=i%n)
{
sum+=A[i];
if(sum==MAGIC_SQUARE_SUM)
return flag-1;
int flag=0;
}
int rowsum(int A[],int i)
{
int x=0,flag=0,temp=0;
for(temp=1;temp<=i;temp++)
{
x+=A[temp];
if(temp%3 ==0)
{
if(x==15)
continue;
else
return flag;
}
}
return (flag=1);
}
columnsum(int A[],int max,int pts,int num)
{
int i=0,j=0,sum=0,flag=0;
for(;i<max;i+=num)
{
sum+=A[j];
if(sum==MAGIC_SQUARE_SUM)
{
j++;
i=j;
if(j>num)
{
return flag=1;
}
}
else
return flag=0;
}
}
void displayrow(int A[],int i)
{
int temp=i/3;
int j=0;
for(j=0;j<i;j++)
{
printf("%d",A[j]);
if((j%3)==0)
printf("\n");
}
}