Question: I want to implement Siamese method generate a magic square which sum of every row, every coloum and two main diagonals sum to the sane
I want to implement "Siamese method" generate a magic square which sum of every row, every coloum and two main diagonals sum to the sane number. ( "Siamese method" : https://en.wikipedia.org/wiki/Siamese_method) It should take user input for the square size.
I'm using C for implementation, but my algorithm run "segmentation fault" each time.
#include
#include
// Structure representing Square
// size: dimension(number of rows/columns) of the square
// array: 2D array of integers
typedef struct _Square {
int size;
int **array;
} Square;
int get_square_size();
Square * generate_magic(int size);
void write_to_file(char *filename, Square * square);
int main(int argc, char *argv[])
{
char buf[100];
int size;
Square* newsquare = generate_magic(get_square_size());
return 0;
}
/* get_square_size prompts the user for the magic square size
* checks if it is an odd number >= 3 and returns the number
*/
int get_square_size()
{
char buf[50];
int size;
printf("Enter size of magic square, must be odd. ");
fgets(buf,sizeof(buf),stdin);
sscanf(buf,"%d", &size);
printf("%d ", size);
return 0;
}
/* generate_magic constructs a magic square of size n
* using the Siamese algorithm and returns the Square struct
*/
Square * generate_magic(int n)
{
Square* ptr = (Square*)malloc(sizeof(Square));
ptr->size = n;
int num = n*n;
int *arr[n];
for(int i = 0; i < n; i++){
arr[i] = (int*)malloc(n*sizeof(int));
}
int mid = n/2 + 1;
arr[0][mid-1] = 1;
int row = 0;
int col = mid;
for(int i = 1; i<= num; i++){
if(row == 0)
row = n-1;
if( (col+1) % n == 0)
col = 0;
if(arr[row][col] != 0)
row = row + n;
if(row > n-1)
row = 0;
arr[row][col] = i;
}
for(int j = 0; j< num; j++){
for (int k = 0; k < num; k++){
printf("%d, ", arr[j][k]);
}
printf(" ");
}
ptr->array = arr;
return ptr;
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
