Question: //A magic square is a n x n square grid (where n is the number of cells on each side) //filled with distinct positive integers
//A magic square is a n x n square grid (where n is the number of cells on each side) //filled with distinct positive integers in the range 1,2,...,n^2, such that each cell //contains a different integer and the sum of the integers in each row, column and diagonal is equal. //In this assignment, we write code to test whether a 1d array contains a n x n magic square //if we treat this array as a 2d array. //This is a good opportunity for us to pratice using 2d arrays. #include
//A naive sorting algorithm //You might need to use this void sort(int A[], int n) { int i, j;
for(i = 0; i < n; i++) for(j = i + 1; j < n; j++) { if(A[i] > A[j]) { int temp; temp = A[i]; A[i] = A[j]; A[j] = temp; } } }
//Test wether the array b contains a n x n magic square int magic_square(int b[], int n) { int i, j; int A[n][n]; int c[n*n];
//Fill in your code below //We need to convert the one dimensional array b[] to an 2d array A[n][n] //and test whether A[n][n] is a n x n magic square //Note we need to check whether all the numbers are in the range of 1 to n*n //Also, we need to check that all numbers are distinct //Last, make sure we do not change contents of the array b[] in the function //The function returns if b[] contains a magic square of size n x n //Otherwise, it returns 0
}
//Do not change the code below int main() { int a[] = {2, 7, 6, 10, 5, 1, 4, 3, 8};
printf("%d ", magic_square(a, 3));
int b[] = {2, 7, 6, 9, 5, 1, 4, 3, 8};
printf("%d ", magic_square(b, 3)); printf("b[0] = %d b[8] = %d ", b[0], b[8]);
int c[] = {2, 16, 13, 3, 11, 5, 8, 10, 7, 9, 12, 6, 14, 4, 1, 15}; printf("%d ", magic_square(c, 4));
int d[] = {1, 16, 13, 3, 11, 5, 8, 10, 7, 9, 12, 6, 14, 4, 1, 15}; printf("%d ", magic_square(d, 4));
int e[9] = {1}; printf("%d ", magic_square(e, 3)); return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
