#Recursive Magic Square Solver

5 messages · Page 1 of 1 (latest)

celest cypressBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

dark otter
#

Your magic function should fill the magic square if possible and return 1. Otherwise, return 0 from the magic function to indicate it was not possible to make a magic square.
#
// This function is a recursive function that intends to solve a given grid[n][n] as in the description.
// Complete the function definition:
int magic(int n, int grid[n][n]) {

}
#

Check function I completed earlier which is also used

#
// This function is a non-recursive function that checks whether a given grid[n][n] is a magic square.
// Complete the function definition:
int check(int n, int grid[n][n]) {
    int expected_sum = (1.0/2.0)*n*(1 + (n*n));

    // Check diagonal sum
    int diagonal_sum = 0;
    for (int i = 0; i < n; i++)
    {
        diagonal_sum += grid[i][i];
    }
    if (diagonal_sum != expected_sum)
    {
        return 0;
    }
    // Check opposite diagonal sum
    diagonal_sum = 0;
    for (int i = 0; i < n; i++)
    {
        diagonal_sum += grid[i][n - 1 - i];
    }
    if (diagonal_sum != expected_sum)
    {
        return 0;
    }
    // Check row sum
    for (int i = 0; i < n; i++)
    {
        int row_sum = 0;
        for (int j = 0; j < n; j++)
        {
            row_sum += grid[i][j];
        }
        if(row_sum != expected_sum)
        {
            return 0;
        }
    }
    // Check col sum
    for (int i = 0; i < n; i++)
    {
        int col_sum = 0;
        for (int j = 0; j < n; j++)
        {
            col_sum += grid[i][j];
        }
        if(col_sum != expected_sum)
        {
            return 0;
        }
    }
    return 1;
}