Search code examples
phpmathnumberspuzzlemagic-square

How to create a magic square in PHP?


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.

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?

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.


Solution

  • 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?

    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.