void placenum(sMatrix mat, int *row, int *col, int num, int size) {
//These are our "mapped" variables.
int maprow, mapcol;
//This is the position in the data vector;
int datavec;
//Initialize our loop to fill the matrix. We're going to begin by first making the middle column of the top
//row a one. Then we're going to move to the right and up and increment until we're done. If its
//full we're going to move down and then continue moving up and right. If we reach the edge we're going to
//"wrap" around like an old Nintendo video game.
if(*row<1) *row =+ size;
if(*col<1) *col += size;
mapcol=*col%size;
maprow=*row%size;
datavec=(maprow-1)*size+mapcol;
if(mat.data[datavec]==NULL) {
mat.data[datavec]=num;
} else {
*col--; *row-=2;
placenum(mat,col,row,num,size);
}
}
sMatrix magic(int size) {
//If size is even, return nothing.
//if((size%2)==0) error("Matrix must be odd");
//Initialize a new matrix to hold our results.
sMatrix result;
result.cols=size;
result.rows=size;
result.data=(double*)malloc(size*size*sizeof(double));
//Initialize loop variable
int loop;
//Use these col and row variables to keep where we're at in the matrix;
int loccol, locrow;
loccol=(int)floor((double)(size/2))+1;
locrow=1;
for(loop=1;loop<=size;loop++) {
placenum(result,&locrow,&loccol,loop,size);
locrow--;
loccol++;
}
return result;
}