首页 > 解决方案 > 测试是否可以从数组创建幻方

问题描述

我正在尝试编写一个程序来检查是否可以从数组中创建幻方。我必须使用的数组包含 64 个元素(这将产生一个 8x8 幻方)。

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)

这给我留下了必须检查 64 的非常明显的问题!不同的排列。

幻方当然具有某些属性。如果它是一个魔方,则可以旋转或反射它,而矩阵不会失去其“魔力”属性。所以如果我检查了一个矩阵,就没有必要检查它的旋转或反射版本。这可以减少可能的排列数量,但需要一种方法来整理某些排列。

也许有人有一个好主意,我可以如何加快我的程序,这样它就不会永远持续下去。

标签: pythonnumpypermutationsympymagic-square

解决方案


推荐阅读