+ 8
[ASSIGNMENT] Magic Square
Magic Square A matrix is called Magic Square if sum of each row equals sum of each columns equals sum of each diagonal without getting any elements repeated, elements should be first n*n positive Integers Tasks :- Easy : Check if input matrix is magic square or not Hard : Take user input n and create n*n magic matrix. Example:- 3Ă3 magic matrix is [8 1 6] [3 5 7] [4 9 2] Where sum of each row=sum of each column=sum of each diagonal=15. P.S. :- Already submitted in assignment section .
16 Answers
+ 5
Here you are : https://code.sololearn.com/cq435Xx5430V
+ 4
~ swim ~ Me too, don't wanna search google and copy some algorithm to make this, trying to figure out in my own way..đ.. you too keep it up..
+ 4
Ouf, finally it seems that I've done it. I've heard long time ago about an approach to fill magic squares of odd size placing numbers diagonally. You can understand the pattern building squares of different size with my code:
https://code.sololearn.com/cJuwuy2wRwQK/?ref=app
Firstly, for any given N it randomly generates a square matrix filled by numbers from 1 to N^2 and then check if this matrix is a magic square. Secondly, if N is odd it generates a true magic square of given size.
Feel free to comment any bugs in a code! ;-)
+ 3
was just testing other ways to do it so code changed while you read. It does test and generation.
https://code.sololearn.com/cq435Xx5430V/?ref=app
+ 3
@swin look at mine. Not very clever but works for n=3 (and larger n but not on sololearn)
+ 3
Basically trying all solutions and stoping a branch when a sum is wrong. Not smart but does the job.
+ 3
~ swim ~ You figured out really nice algorithm, not very hard to implement. Now, Create a program and check if it is valid for all values of n?. I have posted the same assignment for Challanges section. hope they accept it..đđ
+ 1
@VcC Your function makesq(3,9) returns [[2,7,6],[3,4,8],[5,1,9]]. How should I read it to obtain a magic square?
If you think about:
2 7 6
3 4 8
5 1 9
It is not a magic square.