Magic Squares |
We then looked at a program that generates "magic squares" and stores them in two-dimensional lists. A square list 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 list by the following rules:
We are going to place consecutive integer values into cells in the list, 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 list 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 (1..(magicSize * magicSize)) do { nextInt: Number -> // 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 simpler.
Magic Squares |