【问题标题】:PHP Spiral with numbers 0 to 9 [closed]数字 0 到 9 的 PHP Spiral [关闭]
【发布时间】:2011-07-09 04:08:28
【问题描述】:

我正在寻找可以为我编写脚本以输出以下模式的人:

http://img84.imageshack.us/img84/3038/82351644.png

它从中间的 0 开始,然后向左 1,向下 2,向右 3……你明白了。 - 它总是从 0 到 9 并重新开始......

我找到了这个topic,但它显然与我的要求不同。 因为我对 php 没有很好的理解,而“专业人士”在这里, 我很好地问是否有人会花一些时间为我做这件事。 那太好了!此外,如果我可以在变量中设置脚本正在执行多少“轮”,那就太棒了! - 非常感谢

【问题讨论】:

标签: php spiral


【解决方案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 

【讨论】:

  • 这太棒了!非常感谢,您甚至将 cmets 放入您的代码中。我在键盘上对其进行了测试,只需更改尺寸值并看到螺旋增长就非常舒适!太感谢了。 - “我总是喜欢挑战” - 我认为你的精神是正确的!再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多