I have some code that will determine if a N*N list of integers forms a magic square:
import itertools
#Function square magic
def magic_square(matrix):
dimension = len(matrix[0])
sum_list = []
#Horizontal code:
sum_list.extend([sum (lines) for lines in matrix])
#Vertical code:
for col in range(dimension):
sum_list.append(sum(row[col] for row in matrix))
#Diagonals code
diagonal1 = 0
for i in range(0,dimension):
diagonal1 +=matrix[i][i]
sum_list.append(diagonal1)
diagonal2 = 0
for i in range(dimension-1,-1,-1):
diagonal2 +=matrix[i][i]
sum_list.append(diagonal2)
if len(set(sum_list))>1:
return False
return True
m=[[7, 12, 1, 14], [2, 13, 8, 11], [16, 3, 10, 5], [9, 6, 15, 4]]
print(magic_square(m))
m=[[2, 7, 6], [9, 5, 1], [4, 3, 8]]
print(magic_square(m))
m=[[2, 7, 6], [9, 5, 1], [4, 3, 7]]
print(magic_square(m))
print("**************************")
#Now, i use itertools like this:
for i in itertools.combinations(range(1,10), 3):
if sum(i) == 15:
print (i)
# I get the combinations each of three numbers with sum 15
My problem is the last part: I want to generate all permutations of the integers 1 through N^2, break each into a square -- a 2-D list of N rows and N columns -- and use my function to find all magic squares. The itertools code I wrote finds combinations of 3 numbers that will do the job, but I can't figure out the combinatorics to form squares.
Thanks @Prune for your help.
If i have:
[1 5 9]
[1 6 8]
[2 4 9]
[2 5 8]
[2 6 7]
[3 4 8]
[3 5 7]
[4 5 6]
how i can generate an square magic and know if it's True o False, using three at a time the elements of matrix?
Example:
[[1 5 9],[1 6 8], [2 4 9]]
or
[[1 5 9],[1 6 8], [2 5 8]]
or
[[1 5 9],[1 6 8], [2 6 9]] Etcetera, etcetera.
I see -- you want to generate all permutations of magic squares. You need to cover all permutations of the range from 1 through N^2, returned as N lists of N elements each.
This produces a series of candidate squares; feed each one, in turn, to your checking routine, and print the ones that come up True. I expect that you can handle that part.
Here are a few sample candidates from the early part of the generation:
Change of method
Note that this is not your original algorithm: this generates whole squares, rather than just rows of 3. The independent generation has a logic flaw, in that it will generate magic squares that do not include all 9 numbers, while duplicating others. For instance: