/*
程序思想参考百度百科上"幻方法则" 2015-01-27
其实在维基百科上有更全面的,搜索Magic square即可查到,可惜太英语了,有点难,留着以后看^*^
代码环境xcode6.1 playground
几个公用函数只在第一篇显示,后面的篇章不在重复
func isMagic(s:[[Int]])->[Int]?
func printMagic(s:[[Int]])
func signed(aint: Int)->Int
func correction(k: Int, step: Int) ->Int
*/
/*
在居中的方格向上一格内放1,依次向右上方填入2、3、4…,如果右上方已有数字,则向上移两格继续填写。如下图用Louberel法生成的5阶幻方:
23 6 19 2 15
10 18 1 14 22
17 5 13 21 9
4 12 25 8 16
11 24 7 20 3
*/
func JJLouberel(#step: Int) -> ([[Int]])?{
if (step < 3) { return nil}
if (step % 2 == 0) { return nil}
let aRow = [Int](count: step, repeatedValue: 0)
var solution = [[Int]](count: step, repeatedValue: aRow)
//要赋值的位置,初始化为居中的方格向上一格
var row = step/2 - 1 //中间行的上一行
var col = step/2 //中间列
var iPut = 1 //放这个数
//居中的方格向上一格放1
solution[row][col] = iPut++
var time = step * step - 1
do{
//下一个赋值的位置
var nextcol = col + 1
var nextrow = row - 1
nextcol = correction(nextcol,step)
nextrow = correction(nextrow,step)
if solution[nextrow][nextcol] != 0{
nextrow = row - 2
nextrow = correction(nextrow,step)
nextcol = col
if solution[nextrow][col] != 0{
return solution
}
}
row = nextrow
col = nextcol
solution[row][col] = iPut++
}while(time-- > 0)
return nil
}
//测试过程
func testJJLouberel(){
func testAStep(step: Int){
let s = JJLouberel(step: step)
if let s1 = s{
printMagic(s1)
let k = isMagic(s1)
if let k1 = k{
println("这个不是幻方 k=\(k1)")
}
}else{
println("s is not a magic square step = \(step)")
}
}
testAStep(3