How to create a magic square in PHP?

I would like to try my hand at creating Magic Square in PHP (i.e. a grid of numbers that all add to the same value), but I really don't know where to start. I know many methods that create a magic square, for example, starting “1” in a fixed position, and then moving in a certain direction with each iteration. But this does not create a truly randomized Magic Square, which I wanted.

I want to be able to generate an N-by-N magic square of N² numbers, where each row and column are combined in N (N² + 1) / 2 (for example, a 5x5 square, where all rows / columns add up to 65 - the diagonals do not matter) .

Can anyone give a starting point? I don’t want anyone to do this work for me, I just need to know how to start such a project?

I know 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 that I had, was more than 10 years ago. I quickly abandoned it. So I really don't understand what this code does. However, I noticed that when you create a new square, it shows numbers 1-25 (for a 5 × 5 square), before quickly creating a new randomized square.

+3
source share
3 answers

, siamese, . , , . , , ?

, , , . , . , , Java - ​​ - , , Java-.

+2

Java- :

/*
* Magic Square
*/

int order = 5;

for (int row = 0; row < order; row++) {
    for (int col = 0; col < order; col++) {
        int rowMatrix = (((order + 1) / 2 + row + col) % order);
        int colMatrix = (((order + 1) / 2 + row + order - col - 1) %
order) + 1;
        System.out.print(((rowMatrix * order) + colMatrix) + "\t");
    }
    System.out.println(); 

:

  • , 1 nxn . n , 5.
1        2       3       4       5  
6        7       8       9      10
11      12      13      14      15
16      17      18      19      20
21      22      23      24      25
  1. . , , .
4       5       1       2       3               3       2       1       5       4
5       1       2       3       4               4       3       2       1       5
1       2       3       4       5               5       4       3       2       1
2       3       4       5       1               1       5       4       3       2
3       4       5       1       2               2       1       5       4       3

, 1 . 1. .

  1. , . , , 4, 3 ( 2) = 18 ( 1)
18      22       1       10      14
24       3       7       11      20
5        9      13       17      21
6       15      19       23       2
12      16      25        4       8

!

+3

, ?

-: - , . , solve row, , , solveField, , . ( )

solceField 1. , 2. ( , = > )

- , false .

, maqic.

0

Source: https://habr.com/ru/post/1744086/


All Articles