CS 051 Fall 2012

Lecture 26

Magic squares

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.

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.

Image Processing

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.