0

I am trying to write a program that checks if a magic square can be created out of an array. The array that I have to work with contains 64 elements (which would result in a 8x8 magic square).

from sympy.utilities.iterables import multiset_permutations
import numpy as np

def test_if_magic_square(input_matrix):
    # do test here to check if this is a magic square. Returns True or False


if __name__ == '__main__':
    long_array=np.array([...........])
    for p in multiset_permutations(long_array):
        result = test_if_magic_square(p)
        if result:
            print(p)

This leaves me with the very obvious problem of having to check 64! different permutations.

Magic squares have of course certain properties. If it is a magic square it is possible to rotate or reflect it, without the matrix losing its' 'magic' property. So in case I have checked a matrix it wouldn't be necessary to check the rotated or reflected version of it. This could reduce the amount of possible permutations, but it would require a way to sort out certain permutations.

Maybe someone has a good idea how I can speed up my program, so that it doesn't take forever.

ATYslh
  • 75
  • 2
  • 7
  • This is more of a mathematics question. It is doubtful that you can feasibly do anything which requires trial and error. Instead, you need necessary and sufficient conditions on what a sequence of 64 numbers would have to have to be able to form such a square. It is easy to find necessary conditions (e.g. the sum of all the elements needs to be divisible by 8 -- assuming that we are talking about positive integers) but sufficient conditions are harder. Surely it is a studied question, so you could see what is known. – John Coleman May 19 '21 at 12:28
  • @JohnColeman You are probably right about your point. The problem is that basically everything i find relies on the assumption that the magic of size nxn contains the numbers 1...n^2. Looks like I have to continue looking for the right paper/website talking about those properties. – ATYslh May 19 '21 at 12:46
  • An important question is if the 64 numbers in the array are distinct or if there can be repeated elements. For the completely arbitrary case, it might be NP-hard to determine if a collection of n^2 numbers can be arranged into an nxn (generalized) magic square. It seems to involve things like bin-packing (each row is a bin with the magic constant the capacity) but with additional constraints. It also seems to involve subset-sum questions. – John Coleman May 19 '21 at 12:48
  • mathworld has a page on magic squares – smichr May 19 '21 at 14:45

0 Answers0