Monday's Programming Question
This week the programming question is going to extend the Java program from last week's question. If you didn't create that program you can just use my version.
You could be forgiven for thinking that I'm going to ask you to add a new method that creates even magic squares (e.g., 2x2, 4x4, 6x6). However, when it comes to even numbers things can get a little bit tricky so I'm actually going for doubly-even magic squares. Yes, just when you think numbers are either odd or even, someone comes up with the idea of doubly-even. These are numbers that are divisible by four. In terms, of our magic squares these are squares like 4x4, 8x8, 12x12, 16x16 etc..
To make a doubly-even magic square consider the sequence of numbers that make up the square. For example, a 4x4 square is made up of the numbers 1 to 16. If we filled up the square sequentially from the top left corner to the bottom right we would get:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
The trick is to fill the squares according to a generic pattern. Split the magic square so that there is a mini-square at each corner and a large square in the center. The size of a mini-square is the length of the magic square divided by 4 (i.e., for a 4x4 it would be 4/4=1, so each mini-square is a 1x1) and the size of the large square is double the size of the mini-square (i.e., 2x2):
For a 4x4 the pattern is:
# #
# #
# #
# #
Filling in the numbers gives:
1 4 6 7 10 11 13 16
With the remaining numbers in the sequence start at the top row and going from left to right count downwards filling in the squares (i.e., 15,14 fit into the first row, 12,9 into the second row and so on). What you should end up with is:
1 15 14 4 12 6 7 9 8 10 11 5 13 3 2 16
The requirements of the program are to only accept an odd or doubly even number from the user, create the corresponding magic square, and display it to the user along with the magic constant (i.e., the sum of all the numbers in a row or column or diagonal). The creation of the doubly-even magic square should be in its own method. Can your program create the 8 x 8 magic square below?
1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
48 47 19 20 21 22 42 41
40 39 27 28 29 30 34 33
32 31 35 36 37 38 26 25
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64


No comments yet. Leave a Comment