Matrix arrangement issues in php

前端 未结 6 1097
闹比i
闹比i 2021-02-20 13:07

I would like to know some solutions to such a problem.

It is given a number lets say 16 and you have to arrange a matrix this way

1  2  3  4
12 13 14 5
         


        
6条回答
  •  孤城傲影
    2021-02-20 14:13

    In PHP, but with recursion. You can set the size of the square box to be filled by specifying the length of a side.

    The way this works is that the function initially fills in the value at the array location specified. Then it tries to keep moving in the direction it was moving. If it can't, it turns clockwise 90 degrees. If there are no moves left, it stops. This is handled with a switch() statement for the direction variable and recursion.

    This can be adapted to rectangular shaped grids quite easily (just specify 2 constants instead of 1 for the side lengths).

    Live Example with an 8x8 and your 4x4

    The code:

    ";
    for ($y = 0; $y < SIZE; ++$y)
    {
        for ($x = 0; $x < SIZE; ++$x)    
        {
            echo str_pad($array[$x][$y], 4, " ", STR_PAD_BOTH);
        }
        echo "\n";
    }
    echo "
    "; ?>

提交回复
热议问题