2011-07-09 39 views
1

我正在尋找的人誰可以給我寫一個腳本來輸出以下模式:PHP螺旋用數字0到9

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

它從0開始的中心,然後1到左側, 2下,3右...你明白了。 - 它總是0到9,然後重新開始...

我發現這topic,但它明顯不同於我的要求。 因爲我對PHP沒有很好的理解和「優點」在這裏, 我很好地問,如果有人會花一些時間爲我做這個。 那太棒了!另外,如果我可以在變量中設置腳本正在執行的「輪次」數量,那就太棒了! - 非常感謝

+0

你這是什麼[需要](HTTP ://www.catb.org/~esr/faqs/smart-questions.html#goal)這是爲了什麼?你有什麼嘗試? – outis

+0

我試圖解決這個問題 - http://codepad.viper-7.com/6meEJv –

回答

8

只是因爲我沒有什麼好做,我總是喜歡挑戰:

<?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 
+0

這太棒了!非常感謝,你甚至可以在你的代碼中添加註釋。我在鍵盤上測試了它,只是改變尺寸值並看到螺旋不斷增長,這是非常舒適的!非常感謝。 - 「我總是喜歡挑戰」 - 我認爲你有正確的精神!再次感謝! –

+0

@ t.j。 - 別客氣。 –