CS 051 | Fall 2012 |
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:
We then looked at a program that generates
"magic squares"
and stores them in two-dimensional arrays.
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 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.
A number of programs that deal with images and sounds depend on
putting important information in an array and then building a new
array by making changes. A good example of this is a program that can
modify digital music. It is fairly easy to change the tempo or even
the octave of a tune by holding it in a one-dimensional array and then
copying while modifying the sounds.
In class we went over an example
program that helped the
user process images. Operations available were transforming to
grayscale, flipping the image either horizontally or vertically,
blurring the image, or rotating it. One unusual feature of the
program is that we decided to have the first coordinate represent the
column rather than the row, so keep that in mind while reading it.