Information
"... a magic square is an 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, . . . , N2 such that each cell contains a different integer and the sum of the integers in each row, column and diagonal is equal."
Here's an example of a 5 x 5 magic square:
If you add up all of the values in each row, column, and diagonal, you'll see that they all add up to 65. This is the magic sum for the magic square.17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
This practice is programming project 8.17 on page 181 in the textbook. A brief description of the algorithm is as follows:
Start by placing the number 1 in the middle of row 0. Place each of the remaining numbers 2, 3, ..., N2 by moving up one row and over (to the right) one column. Any attempt to go outside the bounds of the array should "wrap around" to the opposite side of the array. If a particular array element is already occupied, put the number directly below the previously stored number.This algorithm is known as the Siamese method or the De la Loubère method. From Wikipedia:
As an example, here is a 3 x 3 array showing each move and how conflicts are resolved. The magic sum is 15:
Notice Move 4: From 3, you move up one row and over one column. Since this spot is already occupied, you put the number 4 one row below the number 3. A similar thing happens when placing the number 7.
Move 1 Move 2 Move 3 . 1 . . . . . . . . 1 . . . . . . 2 . 1 . 3 . . . . 2
Move 4 Move 5 Move 6 . 1 . 3 . . 4 . 2 . 1 . 3 5 . 4 . 2 . 1 6 3 5 . 4 . 2
Move 7 Move 8 Move 9 . 1 6 3 5 7 4 . 2 8 1 6 3 5 7 4 . 2 8 1 6 3 5 7 4 9 2
This is the prototype of the function that the driver will call:
The input, showall, is a flag that determines if you should print all of the moves, instead of just the final square. The return value is the magic sum for the square. Put this function in a file named magic.c and build it with this command line:int magic_square(int size, int showall);
Here is a simple driver file: (main.c, HTML Text) The program requires 2 command line parameters:gcc -O -Werror -Wall -Wextra -ansi -pedantic main.c magic.c -o magic
Examples: (The text from the semi-colon on is just for descriptive purposes)
See the driver to see how it works.magic 5 0 ; Size is 5, just show the final square magic 7 1 ; Size is 7, show all of the squares magic 9 ; Size is 9, just show the final square (default) magic ; Size is 5 (default), just show final square (default)
Here are some sample outputs. The number in the filename is the size of the square. If there is a letter a following the number, it means the file contains all the squares (for debugging purposes).