'幻方'算法 [英] 'Magic Square' algorithm

查看:171
本文介绍了'幻方'算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个实验,我试图创建检查与九个数字每一个可能的方魔方程序。对于那些谁也不知道,幻方是数字1-9,其中每行,列和对角线加起来15。例如一个3x3格:

http://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Magicsquareexample.svg/180px-Magicsquareexample.svg.png

我怎么会去检查用表的Lua每平方?我开始用下面的表格:

 本地平方= {
    1,1,1,
    1,1,1
    1,1,1
}
 

我怎么会去正确的顺序检查每个表?我能够绘制出我的想法在纸面上,但我不完全确定如何将其转化为code。我已经创建了功能检查多是魔力(下),但我不知道如何增加在正确的方式每个号码。谢谢!

 本地isMagic =功能(S)
    返回 (
        S [1] + S [2] + S [3] == 15和
        S [4] + S [5] + S [6] == 15和
        S [7] + S [8] + S [9] == 15和
        S [1] + S [4] + S [7] == 15和
        S [2] + S [5] + S [8] == 15和
        S [3] + S [6] + S [9] == 15和
        S [1] + S [5] + S [9] == 15和
        S [3] + S [5] + S [7] == 15
    )
结束
 

解决方案

根据我所看到这里,有三种方式:

  1),如果我们可以用3定义一步,我们比较列:
和(标签[X]对于x范围内(步骤))==总和(标签[X]对于x中的xrange(步骤+ 1,步* 2))==总和(标签[X]对于x中的xrange(2 *步+ 1,步骤* 3))

2)原糖:
和(标签[X]对于x范围内(步*步)如果x%步骤== 0)==总和(标签[X]对于x范围内(步*步)如果x%步骤== 1)==和(标签[X]对于x范围内(步*步)如果x%步骤== 2)===>直到我们X%一步一步==  -  1

3)Diagonales:
和(标签[X]对于x范围内(步*步)如果x%(步骤+ 1)== 0)==总和(标签[X]对于x范围内(步*步)如果x%(步骤+ 1)==步骤-1)
 

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:

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. Thank you!

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆