如何在PHP中创建魔术方块? [英] How to create a magic square in PHP?

查看:97
本文介绍了如何在PHP中创建魔术方块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尝试用PHP创建一个Magic Square(即,所有数字加起来等于相同值的网格),但我真的不知道从哪里开始.我知道创建魔术方阵的许多方法,例如在固定位置开始"1",然后在每次迭代中沿特定方向移动.但这并不能创建真正随机的魔术广场,这正是我的目标.

I'd like to try my hand at creating a Magic Square in PHP (i.e. a grid of numbers that all add up to the same value), but I really don't know where to start. I know of the many methods that create magic square, such as starting "1" at a fixed position, then moving in a specific direction with each iteration. But that doesn't create a truly randomized Magic Square, which is what I'm aiming for.

我希望能够生成N²个数字的N×N幻方,其中每一行和每一列的总和为N(N²+ 1)/2(例如,所有行/列的总和为5x5的正方形) 65 —对角线没关系).

I want to be able to generate an N-by-N Magic Square of N² numbers where each row and column adds up to N(N²+1)/2 (e.g. a 5x5 square where all rows/columns add up to 65 — the diagonals don't matter).

有人可以提供一个起点吗?我不想让任何人为我做这项工作,我只需要知道如何启动这样的项目?

Can anybody provide a starting point? I don't want anybody to do the work for me, I just need to know how to start such a project?

我知道一个用Java编写的生成器(

I know of one generator, written in Java (http://www.dr-mikes-math-games-for-kids.com/how-to-make-a-magic-square.html) but the last Java experience I had was over 10 years ago before I quickly abandoned it. Therefore, I don't really understand what the code is actually doing. I did notice, however, that when you generate a new square, it shows the numbers 1-25 (for a 5x5 square), in order, before quickly generating a fresh randomized square.

推荐答案

Wikipedia有几种用于生成魔术方块的算法,例如

Wikipedia has several algorithms for generating magic squares, such as the siamese, if you please. But as you say that's not a truly random magic square. It does reference a genetic algorithm, wonder whether you could find more details about that?

您引用的文章使用的方法是使用一些聪明的数学方法,模拟退火.注释中没有解释实际的算法,我也找不到对细节的引用.我可以想象在不了解算法的情况下复制算法,转录现有的Java-实现的核心是很少有方法,数组和算法,几乎没有Java的聪明之处.

The method used by your referenced article is using some clever maths, simulated annealing. The actual algorithm isn't explained in the comments and I can't find any references to the details. I could imagine replicating the algorithm without understanding it, transcribing the existing Java - the core of the implementation is very few methods, arrays and arithmentic hardly any Java cleverness.

这篇关于如何在PHP中创建魔术方块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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