TopMagic squaresGenerating magic squares

Generating magic squares

We then looked at a program that generates "magic squares" and stores them in two-dimensional arrays. A square array of numbers is said to be a "magic square" if all the rows, columns, and diagonals add up to the same number. For example, here is a 3 ×3 magic square:

   4 9 2
   3 5 7
   8 1 6

Each row, column, and diagonal of this square add up to 15.

While it is certainly not obvious, it turns out that there is a straightforward algorithm that will generate a magic square whose width is an odd number. Begin with a 1 in the center of the bottom row, then fill in the remainder of the array by the following rules:

  1. Try to place the next integer (one greater than the last one you placed) in the cell one slot below and one slot to the right of the last place filled. If you fall off the bottom of the array, go to the top row. If you fall off the right edge of the array, go to the leftmost column. If that cell is empty, write the next integer there and continue.
  2. If the cell found above is full, go back to where you wrote the last integer and write the next integer in the cell directly above it.

The method buildArray uses the algorithm described above to generate our magic square.

We are going to place consecutive integer values into cells in the array, beginning with 1. We might consider a nested for loops, adding the values at each position in the same order we used for initialization. But think about our algorithm. It places values in the array starting with 1 and going up to the total number of cells. This sounds like a job for a for loop from 1 to SIZE*SIZE:

    for (int num = 1; num <= SIZE * SIZE; num++) {
      //  insert num into the next cell
    }

See the code for details. However, note how we keep track of what row or column we should be in when we move off of the main board. We use the mod operator to make this simple.


TopMagic squaresGenerating magic squares