PHP Спираль с номерами от 0 до 9
Я ищу человека, который мог бы написать мне скрипт для вывода следующего шаблона:
http://img84.imageshack.us/img84/3038/82351644.png
начиная с 0 в центре, затем 1 слева, 2 вниз, 3 вправо... вы поняли. - всегда от 0 до 9 и начинается снова...
Я нашел эту тему, но она явно отличается от моей просьбы. Так как у меня нет хорошего понимания php и здесь есть "плюсы", я спрашиваю, хорошо, если бы кто-то потратил некоторое время, делая это для меня. Это было бы прекрасно! Также, если бы я мог установить в переменной, сколько "раундов" выполняет скрипт, это было бы здорово! - Большое спасибо
1 ответ
Решение
Просто потому, что у меня не было ничего лучше, и мне всегда нравятся проблемы:
<?php
// A few constants.
define('DOWN', 0);
define('LEFT', 3);
define('RIGHT', 1);
define('UP', 2);
// Dictates the size of the spiral.
$size = 11;
// The initial number.
$number = 0;
// The initial direction.
$direction = RIGHT;
// The distance and number of points remaining before switching direction.
$remain = $distance = 1;
// The initial "x" and "y" point.
$y = $x = round($size / 2);
// The dimension of the spiral.
$dimension = $size * $size;
// Loop
for ( $count = 0; $count < $dimension; $count++ )
{
// Add the current number to the "x" and "y" coordinates.
$spiral[$x][$y] = $number;
// Depending on the direction, set the "x" or "y" value.
switch ( $direction )
{
case LEFT: $y--; break;
case UP: $x--; break;
case DOWN: $x++; break;
case RIGHT: $y++; break;
}
// If the distance remaining is "0", switch direction.
if ( --$remain == 0 )
{
switch ( $direction )
{
case DOWN:
$direction = LEFT;
$distance++;
break;
case UP:
$distance++;
default:
$direction--;
break;
}
// Reset the distance remaining.
$remain = $distance;
}
// Increment the number or reset it to 0 if the number is 9.
if ( $number < 9 )
$number++;
else
$number = 0;
}
// Sort by "x" numerically.
ksort($spiral, SORT_NUMERIC);
foreach ( $spiral as &$x )
{
// Sort by "y" numerically.
ksort($x, SORT_NUMERIC);
foreach ( $x as $ykey => $y )
// Output the number.
echo $y . ' ';
// Skip a line.
echo PHP_EOL;
}
Выходы:
0 1 2 3 4 5 6 7 8 9 0
9 2 3 4 5 6 7 8 9 0 1
8 1 2 3 4 5 6 7 8 9 2
7 0 1 0 1 2 3 4 5 0 3
6 9 0 9 6 7 8 9 6 1 4
5 8 9 8 5 0 1 0 7 2 5
4 7 8 7 4 3 2 1 8 3 6
3 6 7 6 5 4 3 2 9 4 7
2 5 6 5 4 3 2 1 0 5 8
1 4 3 2 1 0 9 8 7 6 9
0 9 8 7 6 5 4 3 2 1 0