-
Magic Square
I have written some code (please see below) to create a magic square. The only way I could figure out how to complete it while using functions included using double and triple pointers. Can someone please give me a suggestion on how to eliminate the double and triple pointers.
#include <stdio.h>
#include <stdlib.h>
void allocate(int ***, int);
void create_square(int **, int);
int main(void)
{
int **matrix;
int size;
int i;
printf("Enter an odd number for the size of the matrix: ");
scanf("%d", &size);
printf("\n\n");
allocate(&matrix, size);
create_square(matrix, size);
for (i = 0; i < size; i++)
free(matrix[i]);
free(matrix);
return 0;
}
void allocate(int ***mat, int s)
{
int i, k;
int **pmat;
pmat = malloc(s * sizeof(*pmat));
for (i = 0; i < s; ++i)
pmat[i] = malloc(s * sizeof(**pmat));
for (i = 0; i < s; i++)
for (k = 0; k < s; k++)
pmat[i][k] = 0;
*mat = pmat;
}
/* move up (decrement index), wrapping if necessary */
int move_up(int cur, int s)
{
if (cur == 0)
return s - 1;
return cur - 1;
}
/* move right (increment index), wrapping if necessary */
int move_right(int cur, int s)
{
if (cur == s - 1)
return 0;
return cur + 1;
}
/* pointer just to have a conveniently-named alias for the same function */
int (*move_down)(int, int) = move_right;
void create_square(int **mat, int s)
{
int j = 0;
int k = s / 2; /* middle for odd numbers only */
int i, lk, lj;
for (i = 1; i <= s*s; i++)
{
mat[j][k] = i;
/* save the last position in case the new is already set */
lj = j;
lk = k;
/* move */
j = move_up(j, s);
k = move_right(k, s);
/* if new position is already set, go back to last and move down */
if (mat[j][k] != 0)
{
j = move_down(lj, s);
k = lk;
}
/* back to top for assignment */
}
/* print matrix */
for (j = 0; j < s; j++)
{
for (k = 0; k < s; k++)
printf("%d ", mat[j][k]);
printf("\n");
}
}
-
Well you could start off with something simple like
Code:
int matrix[11][11];
int size;
printf("Enter an odd number for the size of the matrix (<=11): ");
scanf("%d", &size);
For what it's worth, your allocate is actually correct
-
Magic Square
I give this problem to my C++ students sometimes. Salem is right on how you should start off.
Some questions:
Do you want to generate the actual square as well as the magic number?
Or
Do you want to just check the rows and columns to verify that the square is actually magic.
Finally, try creating even magic squares. Not all numbers can be done. but it is worth the effort!!