I can find only one magic square how to find all please.
Asked
Active
Viewed 1,327 times
-7
-
4welcome to stackoverflow! this is not a code writing service, please provide what you have tried so far and where exactly you are stuck. furthermore, please check out this answer on how to _properly_ ask a homework questions --> https://meta.stackoverflow.com/a/334823/6817835 – gold_cy Jun 12 '19 at 13:29
-
2Welcome to StackOverflow. This question is missing context or other details: Please improve the question by providing additional context, which ideally includes your thoughts on the problem and any attempts you have made to solve it. This information helps others identify where you have difficulties and helps them write answers appropriate to your experience level. You also need to state exactly what your difficulty is, what you expected, what you got, and any traceback. – Rory Daulton Jun 12 '19 at 13:32
-
3Also, you should define just what you mean by a "magic square." I have seen multiple definitions. – Rory Daulton Jun 12 '19 at 13:33
2 Answers
2
I'll leave finding out how to generate a magic square as an exercise. If you're still having trouble with it, you can find other questions on StackOverflow about how to generate a magic square of a given size in Python.
Once you have your 3x3 magic square magic(3)
(as a numpy ndarray), you can obtain all of the possible magic squares of that size by performing all of the possible rotations and reflections on it:
rotations = [np.rot90(magic(3), x) for x in range(4)]
reflections = [np.flip(x, 1) for x in rotations]
all_magic_3x3 = rotations + reflections
This produces a list containing the following 8 magic 3x3 matrices:
[[8 1 6]
[3 5 7]
[4 9 2]]
[[6 7 2]
[1 5 9]
[8 3 4]]
[[2 9 4]
[7 5 3]
[6 1 8]]
[[4 3 8]
[9 5 1]
[2 7 6]]
[[6 1 8]
[7 5 3]
[2 9 4]]
[[2 7 6]
[9 5 1]
[4 3 8]]
[[4 9 2]
[3 5 7]
[8 1 6]]
[[8 3 4]
[1 5 9]
[6 7 2]]

Will Da Silva
- 6,386
- 2
- 27
- 52
0
from itertools import permutations
def generate_all_magic_squares():
magic_squares = []
for seq in permutations(range(1, 10)):
cand = [seq[i:i+3] for i in range(0, 9, 3)]
# filter cand whose row sum is a const
if sum(cand[0]) == sum(cand[1]) == sum(cand[2]):
cols = list(zip(*cand)) # invert cols to rows to check their sums as well
if sum(cols[0]) == sum(cols[1]) == sum(cols[2]) == sum(cand[0]):
pd = [cand[0][0],cand[1][1],cand[2][2]] # principle diagnol
od = [cand[0][2], cand[1][1], cand[2][0]] # other diagnol
if sum(pd) == sum(od) == sum(cand[0]): # check the sums of the diagnol are equal to other rows/cols
magic_squares.append(cand)
return magic_squares

mwikya
- 86
- 1
- 3