假设我有$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