Question

Write a Python program that generate randomly a magic square of 3 x 3 elements. For...

Write a Python program that generate randomly a magic square of 3 x 3 elements. For example:

4

3

8

9

5

1

2

7

6

    

= Matrix1

Matrix 1 above is an example of magic square. The rows total, the columns total, and the diagonal totals are all 15.

Your program should randomly generate a 3x3 matrix. Check if it is a magic square. If it is a magic square, then print some information and quit. If the generated square is not magic, then increment the counter of the tries, print it, and try again. Keep on trying until you find a magic square. Your program should keep on trying automatically until it finds a magic square.

I attached a Python program with informal description and algorithm of how the program should work. You may copy it and use it to write the program. If you want to start from scratch and built your own program, you can do that as long as you use a random function to create a 3x3 matrix, then test it if it is a magic square, and finally print it with required information whenever it is found.

Below is what your program should display on the screen when you run it.

1

2

3

:

:

:

82222

82223

82224

It is a magic square

[[6, 7, 2], [1, 5, 9], [8, 3, 4]]

It started at : 1584806306.7437787 using seconds

It ended   at : 1584806608.498532 using seconds

It started at : Sat Mar 21 11:58:26 2020

It ended   at : Sat Mar 21 12:03:28 2020

It took 301 seconds to find the magic square

Notice that we have a billion option to test a 9 digits’ number. In the example above, it took 82,224 tries to find that magic square. The time required to do these many random combination and test them is 301 seconds, which is equal to 5 minutes.

Your program may find the magic square in a different number of tries of course, since it is random.

Below is a copy of the attached Python magic square program that you may start with.

--------------------------------Beginning of the Python program-------------------------------

# Name

# Date

# Magic Squre Program

import random

import time

tim_st=time.time()

tim_st2=time.ctime()

s=0 # s is a counter that prints how many tries have been made

while True: # keep trying until you find a magic square

    magic=True # assume that magic is True, as a start

    mat1=[] # intialize matrix1 (mat1) to hold 9 unique numbers

    i=1

    while i < 10:

        # generate a random number between 1 and 9

        # check if the generated number exists in the list, if it exists try

        # again, if it doesn't exist in the list then append it to the list

    # intialize mat2 Multi-dimensional list with

    # 3 rows and 3 columns

    # Transfer the nine random number into the mat2 in order 3 x 3 x 3  

    ''' this is two possible magic squares

        matrix=[[2,7,6],[9,5,1],[4,3,8]]

        matrix=[[6,1,8],[7,5,3],[2,9,4]]

    '''   

    ##### Sum of the first row, call it sum1

    ##### Sum of rows, and check if each row's sum equal to sum1

    ##### Sum of columns, and check if each column's sum equal to sum1       

    ##### Sum of first Diagonal, and check if the sum equal to sum1

    ##### Sum of second Diagonal, and check if the sum equal to sum1

    # if it is a magic square:

    # 1- print the magic square

    # 2- print the time it took to find one randomly

    # 3- break out of the loop, STOP the program

    # increment the counter 's' of tries and print it

   

--------------------------------End of the Python program-------------------------------

There are many programs available in the WWW to generate magic square according to some known patterns. You are not asked to copy any of them.

You are asked to use a random function to generate a 3x3 matrix, then check if it is a magic square, and keep on trying until you get one.

Any other algorithm you use to write the program will not be accepted if you don’t use the requested random generating algorithm.

This assignment gives you a chance to exercise on simulation of a problem in your field of specialty according to some given factors where you may notice the result according to random sample set of data.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import random
import time
import numpy as np

time_st=time.time()
time_with_date_st=time.ctime()

try_counter = 0

while True:
    try_counter += 1
    mat = random.sample(range(1, 10), 9) #Generating 9 random number between 1 to 9
    magic_sqr = np.reshape(mat, (3, 3)) #reshaping the list to 3*3 matix
    row_sum = np.sum(magic_sqr,axis=1) #take sum of the all row individually
    col_sum = np.sum(magic_sqr,axis=0) #take sum of the all column individually
    diag_sum1 = np.trace(magic_sqr) #take sum of the main diagonal elements
    diag_sum2 = magic_sqr[::-1].trace() #take sum of the secondary diagonal elements
    if row_sum[0] != row_sum[1] or row_sum[0] != row_sum[2]: # checking all the row sum are equal or not
        print(try_counter)
        continue
    if col_sum[0] != col_sum[1] or col_sum[0] != col_sum[2]: # checking all the column sum are equal or not
        print(try_counter)
        continue
    if diag_sum1 != diag_sum2: ## checking sum of the both diagonals are equal or not
        print(try_counter)
        continue
    print(try_counter)
    print(magic_sqr)
    end_time = time.time()
    time_with_date_end = time.ctime()
    time_diff = round((end_time - time_st),3)
    print("It started at:"+ str(time_st) + " using seconds")
    print("It ended at:"+ str(end_time) + " using seconds")
    print("It started at:"+ time_with_date_st)
    print("It ended at:"+ time_with_date_end)
    print("It took "+ str(time_diff) +" seconds to find the magic square")
    break

Add a comment
Know the answer?
Add Answer to:
Write a Python program that generate randomly a magic square of 3 x 3 elements. For...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Use basic java for this after importing PrintWriter object You will make a simple Magic Square...

    Use basic java for this after importing PrintWriter object You will make a simple Magic Square program for this Java Programming Assignment. Carefully read all the instructions before beginning to code. It is also required to turn in your pseudocode or a flowchart along with this program. Here are the instructions: At the beginning of the program, briefly describe to the user what a Magic Square Matrix is (described further on), and then allow them to enter “start” to begin...

  • PYTHON 3: An n x n matrix forms a magic square if the following conditions are...

    PYTHON 3: An n x n matrix forms a magic square if the following conditions are met: 1. The elements of the matrix are numbers 1,2,3, ..., n2 2. The sum of the elements in each row, in each column and in the two diagonals is the same value. Question: Complete the function that tets if the given matrix m forms a magic square. def is_square(m): '''2d-list => bool Return True if m is a square matrix, otherwise return False...

  • IN C++ Write a program that uses a 3x3 array and randomly places each integer from...

    IN C++ Write a program that uses a 3x3 array and randomly places each integer from 1 to 9 into the nine squares. The program calculates the "magic number" by adding all the numbers in the array and then dividing the sum by 3. The 3x3 array is said to be a "magic square" if the sum of each row, each column, and each diagonal is equal to the magic number. Your program must use at least the following functions:...

  • C++: Write a program that uses a 3 X 3 array and randomly place each integer...

    C++: Write a program that uses a 3 X 3 array and randomly place each integer from 1 to 9 into the nine squares. The program calculates the magic number by adding all the numbers in the array and then dividing the sum by 3. The 3 X 3 array is a magic square if the sum of each row, each column, and each diagonal is equal to the magic number. Your program must contain at least the following functions:...

  • 9. Lo Shu Magic Square The Lo Shu Magic Square is a grid with three rows and three columns that h...

    9. Lo Shu Magic Square The Lo Shu Magic Square is a grid with three rows and three columns that has the following properties: The grid contains the numbers 1 through 9 exactly. The sum of each row, each column, and each diagonal all add up to the same number. This is shown in the following figure · 15 4 9 2-15 3 5 7-15 81 615 15 15 15 15 Write a program that simulates a magic square using...

  • Write a C++ program that uses a 4 X 4 array and randomly place each integer...

    Write a C++ program that uses a 4 X 4 array and randomly place each integer from 1 to 16 into the 16 squares. The program calculates the magic number by adding all the numbers in the array and then dividing the sum by 4. The 4 X 4 array is a magic square if the sum of each row, each column and each diagonal is equal to the magic number. Your program must contain at least the following functions...

  • Help pls! and kindly explain how you do this as well. Thaank you Write a program...

    Help pls! and kindly explain how you do this as well. Thaank you Write a program to test whether a square is a 3x3 magic square. A magic square is a grid with 3 rows and 3 columns, like the figure below. A magic square has the following properties: the grid contains only the numbers 1 through 9 the sum of each row, each column, and each diagonal all add up to the same number Notes: I have provided the...

  • Read your notes concerning 2D arrays with particular attention to the syntax of passing arrays as...

    Read your notes concerning 2D arrays with particular attention to the syntax of passing arrays as parameters to functions. Write the pseudocode (algorithm) for the following program definition: A text file contains a square matrix of integer numbers. The file contains an integer number indicating the identical number of rows and columns followed by the data itself (that number cannot be larger than 100). For example, a file containing a 3x3 matrix would contain 3 followed by 9 other integer...

  • Magic Squares; Java code

    Magic squares. An n × n matrix that is filled with the numbers 1, 2, 3, ..., n2 is a magic square if the sum ofthe elements in each row, in each column, and in the two diagonals is the same value. For example,16 3 2 135 10 11 89 6 7 124 15 14 1Write a program that reads in n2 values from the keyboard and tests whether they form a magic squarewhen arranged as a square matrix. You...

  • please use java language please used ArrayList The Lo Shu Magic Square is a grid with...

    please use java language please used ArrayList The Lo Shu Magic Square is a grid with 3 rows and 3 columns, shown in Figure 7-31. The • The sum of each row, each column, and each diagonal all add up to the same number 20. Lo Shu Magic Square Lo Shu Magic Square has the following properties: • The grid contains the numbers 1 through 9 exactly. This is shown in Figure 7-32. In a program you can simulate a...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT