Tic Tac Toe and Magic Squares |
We first looked at a tic-tac-toe program to see how to access the elements of a two dimensional array. Examining this program showed how to map from the location of a mouse click to a row and column in a two-dimensional array and how to traverse a row, column, or diagonal of a two-dimensional array.
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:
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.
Tic Tac Toe and Magic Squares |