Reputation: 1
I can find only one magic square how to find all please.
Upvotes: -7
Views: 1888
Reputation: 96
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
Upvotes: 0
Reputation: 7030
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]]
Upvotes: 2