+ 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 .

28th Apr 2018, 4:50 AM
Zoetic_Zeel
Zoetic_Zeel - avatar
16 Answers
28th Apr 2018, 5:28 PM
LukArToDo
LukArToDo - avatar
28th Apr 2018, 10:08 PM
VcC
VcC - avatar
+ 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..
29th Apr 2018, 5:10 AM
Zoetic_Zeel
Zoetic_Zeel - avatar
+ 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! ;-)
30th Apr 2018, 1:14 AM
Nevfy
+ 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
28th Apr 2018, 11:43 PM
VcC
VcC - avatar
+ 3
@swin look at mine. Not very clever but works for n=3 (and larger n but not on sololearn)
29th Apr 2018, 6:55 AM
VcC
VcC - avatar
+ 3
Basically trying all solutions and stoping a branch when a sum is wrong. Not smart but does the job.
29th Apr 2018, 7:35 AM
VcC
VcC - avatar
+ 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..😀😀
29th Apr 2018, 7:54 AM
Zoetic_Zeel
Zoetic_Zeel - avatar
+ 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.
28th Apr 2018, 11:38 PM
Nevfy