假設我有$rows = 4
,並且$cols = 4;
,如何在一個螺旋爲了創建一個具有16個元素數組,如:PHP - 創建一個螺旋
1, 2, 3, 4,
12,13,14,5,
11,16,15,6,
10,9, 8, 7,
假設我有$rows = 4
,並且$cols = 4;
,如何在一個螺旋爲了創建一個具有16個元素數組,如:PHP - 創建一個螺旋
1, 2, 3, 4,
12,13,14,5,
11,16,15,6,
10,9, 8, 7,
使用的載體和布爾值。迭代X軸開始,直到到達行的末尾。在遍歷它時,將每個位置的值設置爲true。任何時候當你到達邊界或布爾真時,向右轉。
所以,第一行的「載體」將在X增量變爲零和Y增量爲1,那麼你會在每一輪檢查增量的價值和容納4種情景。
這是我想到的第一種方式。
第二種方法不會用布爾值,而是會簡單地跟蹤有多少列或行留在光標的路徑上的前,減少X或Y在每回合剩餘。其餘的邏輯將保持不變。
當你到達中心,你會打一個循環,有沒有更多的迭代可能。您可以通過驗證廣場周圍的可能性數量,或者簡單地從您開始的N個總平方中倒數,並在數字爲零時停止。
您可以將上述方法用於任何尺寸的正方形。
該算法不是非常困難。您必須重複從1
到$rows*$cols
。在迭代過程中,您必須計算矩陣($x,$y)
中當前數字的位置。首先將在(1,1)
當然。因爲你在往東走,所以下面的一條將是($x+1,$y)
。所以,每個數字的位置是基於前一個的位置和正確的方向。
算法的棘手部分是計算方向。但是如果你看看它,你會看到每次碰到使用過的單元時順時針方向改變,或者你超出界限。
總而言之,這將是〜PHP代碼的30行。
我希望這會有所幫助。
PHP中的高爾夫球類似的挑戰:http://www.phpgolf.org/challenge/Spiral。有人只用130個字符解決了它!
我的解決方案非常冗長,因爲您的目的是讓您檢查它並瞭解它是如何工作的。
<?php
/**
* Creates a 2D array with the given dimensions,
* whose elements are numbers in increasing order
* rendered in a 'spiral' pattern.
*/
function createSpiral($w, $h) {
if ($w <= 0 || $h <= 0) return FALSE;
$ar = Array();
$used = Array();
// Establish grid
for ($j = 0; $j < $h; $j++) {
$ar[$j] = Array();
for ($i = 0; $i < $w; $i++)
$ar[$j][$i] = '-';
}
// Establish 'used' grid that's one bigger in each dimension
for ($j = -1; $j <= $h; $j++) {
$used[$j] = Array();
for ($i = -1; $i <= $w; $i++) {
if ($i == -1 || $i == $w || $j == -1 || $j == $h)
$used[$j][$i] = true;
else
$used[$j][$i] = false;
}
}
// Fill grid with spiral
$n = 0;
$i = 0;
$j = 0;
$direction = 0; // 0 - left, 1 - down, 2 - right, 3 - up
while (true) {
$ar[$j][$i] = $n++;
$used[$j][$i] = true;
// Advance
switch ($direction) {
case 0:
$i++; // go right
if ($used[$j][$i]) { // got to RHS
$i--; $j++; // go back left, then down
$direction = 1;
}
break;
case 1:
$j++; // go down
if ($used[$j][$i]) { // got to bottom
$j--; $i--; // go back up, then left
$direction = 2;
}
break;
case 2:
$i--; // go left
if ($used[$j][$i]) { // got to LHS
$i++; $j--; // go back left, then up
$direction = 3;
}
break;
case 3:
$j--; // go up
if ($used[$j][$i]) { // got to top
$j++; $i++; // go back down, then right
$direction = 0;
}
break;
}
// if the new position is in use, we're done!
if ($used[$j][$i])
return $ar;
}
}
/**
* Assumes the input is a 2D array.
*/
function print2DGrid($array) {
foreach ($array as $row) {
foreach ($row as $col) {
print sprintf("% 2d ", $col);
}
print "\n";
}
}
$width = 12;
$height = 8;
print2DGrid(createSpiral($width, $height));
?>
Here it is在行動上,使下面的輸出:
0 1 2 3 4 5 6 7 8 9 10 11
35 36 37 38 39 40 41 42 43 44 45 12
34 63 64 65 66 67 68 69 70 71 46 13
33 62 83 84 85 86 87 88 89 72 47 14
32 61 82 95 94 93 92 91 90 73 48 15
31 60 81 80 79 78 77 76 75 74 49 16
30 59 58 57 56 55 54 53 52 51 50 17
29 28 27 26 25 24 23 22 21 20 19 18
希望這有助於。
@RebeccaBlack在主導音樂排行榜之後,你現在正在用PHP試試你的手? :) – alex 2011-04-30 17:07:23
這是一個螺旋? – GSto 2011-04-30 17:07:36
這是作業,我相信 – 2011-04-30 17:08:02