int is_magic_square(Matrix *A){ //Case that rows and columns not the same //Not a Square grid, so cannot be square if (A->rows != A->cols){ printf("Not a square matrix\n"); return 0; } //Getting sum of rows double *allRowSum = row_sum(A); //Get sum of columns double *allColSum = col_sum(A); //Get sum of diagnols double *allDiag = diag_sum(A); //Get total of first row - all others should be the same either way double magic = allRowSum[0]; if (test_rows(allRowSum, A->rows, magic)){ if (test_cols(allColSum, A->cols, magic)){ if (test_diag(allDiag, magic)){ //If rows, cols, and diags are the same //We have a magic square! return 1; } } } return 0; }
/* http://en.wikipedia.org/wiki/Magic_square A magic square is an arrangement of numbers (usually integers) in a square grid, where the numbers in each row, and in each column, and the numbers in the forward and backward main diagonals, all add up to the same number. Write a function called is_magic_square() that takes a matrix and returns an int, 1 if the matrix is a magic square, and 0 otherwise. Feel free to use row_sum(). */ int is_magic_square(Matrix *M) { // adding rows should be fastest due to caching, check that first double *row_sums = row_sum(M); double magnum = row_sums[0]; if (!is_uniform_vector(row_sums,M->rows,magnum)) { return 0; } free(row_sums); // tidy tidy // adding columns is slower, since it's more likely for the data to be // spatially distant double *col_sums = col_sum(M); if (!is_uniform_vector(col_sums,M->cols,magnum)) { return 0; } free(col_sums); double *diag_sums = diag_sum(M); return (diag_sums[0] == magnum) && (diag_sums[1] == magnum); }