A collection of tricks, thoughts, ideas and solutions from a graphics programmer. This blog contains my experiences, tips and tricks, everyday problems and their solutions. This blog serves not only as my reference but also for the whole world at large.
Saturday, October 25, 2008
Odd Magic Square NxN C++ code
The blogger interface is stupid it keeps formatting my input so I am attaching the whole cpp file. Get the C++ Code. Ofcourse rename the file remove the .zip extension
Magic Squares Algorithm & C++ implementation
Hi all,
This time around its something a bit tricky generating an odd magic square. Details are given everywhere. The wiki entry is sufficient, check it out http://en.wikipedia.org/wiki/Magic_square.
I base on the same logic which is commonly followed the one up one right stepping strategy. Here is the pseudocode,
This time around its something a bit tricky generating an odd magic square. Details are given everywhere. The wiki entry is sufficient, check it out http://en.wikipedia.org/wiki/Magic_square.
I base on the same logic which is commonly followed the one up one right stepping strategy. Here is the pseudocode,
//n is the dimension of magic square for a 3*3 square n=3;
int magic[n][n]={0};
curRow=0, curCol=1;
oldRow=0, oldCol=0;
count =0;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
//See if we are into an empty cell
if( magic[curRow][curCol]==0 )
{
magic[curRow][curCol] = ++count;
}
else
{
//Move down from the previous row but keep the same column
magic[(oldRow+1)%n][oldCol] = ++count;
curRow = (oldRow+1)%n;
curCol = oldCol;
}
//Store the last row and column index
oldRow=curRow;
oldCol=curCol;
//Move one up and one right
curRow=(curRow-1)%n;
curCol=(curCol+1)%n;
//Wrap around the size
if(curRow<0)
curRow =n-1;
}
}