A n x n matrix that is filled with the numbers 1, 2, 3, ..., n² is a magic square if the sum of the elements in each row, in each column, and in the two diagonals is the same value.
Implement the following algorithm to construct the magic n-by-n squares. This algorithm works only if n is odd.
The purpose of this assignment is two-fold - generate odd dimension magic squares using the above algorithm and generating all possible magic squares for a given dimension using brute force (in this case through permutation). We will use small numbers to test your implementation of the algorithm - 3, 5, 7, and 9. For the brute force method you will generate all 3x3 magic squares.
The skeleton of your program will be as follows:
# Populate a 2-D list with numbers from 1 to n2 def makeSquare ( n ): # Print the magic square in a neat format where the numbers # are right justified def printSquare ( magicSquare ): # Check if a list is a magic square and print def checkSquare ( magicSquare ): # Generate all 3x3 magic squares def permute (a, lo); def main(): # Prompt the user to enter an odd number 3 or greater # Check the user input # Create the magic square # Print the magic square # Print all 3x3 magic squares main()
In your function main() you will prompt the user to enter an odd number. You must check that the input is a positive odd number greater than or equal to 3. If it is not, you will prompt the user to re-enter the number and check again and again.
Then you will create a 2-D list representing the Magic Square. You will then print out the magic square in a neat format by calling the function printSquare(). In the function printSquare() you MUST use print with formatting. Assume that the largest number that you will be printing is a 2-digit number.
You will then call the function permute(). This function will generate all permutation of the list [1 2 3 4 5 6 7 8 9]. The function checkSquare() will test if a given permutation is a magic square. If it is, then it will print out the magic square in a neat format.
This is a sample of what the program will output:
Please enter an odd number: 5 Here is a 5 x 5 magic square: 11 18 25 2 9 10 12 19 21 3 4 6 13 20 22 23 5 7 14 16 17 24 1 8 15 All 3x3 magic square: 4 9 2 3 5 7 8 1 6 .. .. .. .. .. ..
The file that you will be turning in will be called MagicSquare.py. The file will have a header of the following form:
# File: MagicSquare.py # Description: # Student's Name: # Student's UT EID: # Course Name: CS 313E # Unique Number: 53580 # Date Created: # Date Last Modified:
Use the turnin program to submit your MagicSquare.py file. We should receive your work by 11 PM on Wednesday, 19 March 2014. We will be looking for clean logic and good documentation. There will be substantial penalties if you do not adhere to the guidelines. The student assistant in charge of this assignment is Devin Sandhu (email@example.com).