前几天一个同事面试,让写一个由内向外回环,现代码为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| <?php function printNumbers($n){ $y = $x = ($n - 1) / 2; $num = 2; $total = pow($n, 2); $arr = array_fill(0, $n, array_fill(0, $n, 1)); $i = 0; $limit = 1;
while ($num <= $total) { for ($j = 0; $num <= $total && $j < $limit; ++$j) { switch ($i) { case 0 : ++$y; break; case 1 : ++$x; break; case 2 : --$y; break; case 3 : --$x; break; } $arr[$x][$y] = $num++; } if ($i % 2 == 1) { ++$limit; } $i = ($i + 1) % 4; }
for ($i = 0; $i < $n; $i ++) { foreach ($arr[$i] as $item) { if ($item < 10) { $item = $item . " "; } echo " " . " $item " . " "; } echo "</br>"; } }
|