“魔方"算法 [英] 'Magic Square' algorithm
问题描述
作为一项实验,我正在尝试创建一个幻方程序,用九个数字检查每个可能的方格.对于那些不知道的人来说,幻方是一个由 1-9 数字组成的 3x3 网格,其中每行、每列和对角线的总和为 15.例如:
As an experiment, I'm trying to create a magic square program that checks every possible square with nine numbers. For those who do not know, a magic square is a 3x3 grid of numbers 1-9, where each row, column, and diagonal add up to 15. For example:
我将如何使用 Lua 使用表格检查每个方块?我从下表开始:
How would I go about checking each square using a table with Lua? I'm starting with the following table:
local sq = {
1, 1, 1,
1, 1, 1
1, 1, 1
}
我将如何以正确的顺序检查每张桌子?我能够在纸上画出我的想法,但我不完全确定如何将其转换为代码.我已经创建了检查正方形是否神奇"的函数(如下),但我不确定如何以正确的方式增加每个数字.
How would I go about checking each table in the correct order? I'm able to draw out my thinking on paper, but I'm not completely sure how to translate it to code. I already created the function to check if the square is 'magic' (following), but I'm not sure how to increase each number in the correct fashion.
local isMagic = function(s)
return (
s[1] + s[2] + s[3] == 15 and
s[4] + s[5] + s[6] == 15 and
s[7] + s[8] + s[9] == 15 and
s[1] + s[4] + s[7] == 15 and
s[2] + s[5] + s[8] == 15 and
s[3] + s[6] + s[9] == 15 and
s[1] + s[5] + s[9] == 15 and
s[3] + s[5] + s[7] == 15
)
end
推荐答案
根据我在这里看到的,共有三种模式:
Based on what I am seeing here, there are three patterns:
1) if we can define step by 3, we compare columns:
sum(tab[x] for x in range(step)) == sum(tab[x] for x in xrange(step+1,step*2))== sum(tab[x] for x in xrange(2*step+1,step*3))
2) raws:
sum(tab[x] for x in range(step*step) if x%step==0) == sum(tab[x] for x in range(step*step) if x%step==1)== sum(tab[x] for x in range(step*step) if x%step==2) ===> till we x%step== step-1
3) Diagonales:
sum(tab[x] for x in range(step*step) if x%(step+1)==0) == sum(tab[x] for x in range(step*step) if x%(step+1)==step-1)
这篇关于“魔方"算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!