3

我正在尝试制作一个提供如下输出的程序:

X

xx

xxx

xxxx

xxxxx

xxxx

xxx

xx

X

我有一个类似的程序是:

<?php
    $n = 4;                                     
    $R[] = '*';                                  
    $w = 1;                                     
        for( $c=1; $c<=$n; $c++ ){             
            $R[] = '*'.str_repeat( '*',$w );  
            $w = $w+1;                       
        }        
    print '<pre>'.implode( "\n",$R ).'</pre>';  
?>

但我需要使用一个函数并创建另一个循环以获得更简单的代码。我还需要在第 5 行之后减少它。提前谢谢...

4

5 回答 5

4

鉴于问题描述,我只会使用递归,因为它是一种更优雅的方式。

function hump($n, $i = 1)
{
        echo str_repeat('*', $i), PHP_EOL;
        if ($i < $n) {
                hump($n, $i + 1);
                echo str_repeat('*', $i), PHP_EOL;
        }
}

hump(5);

它在每次调用中打印一个级别,并调用自己打印下一个级别,直到它到达顶部;当堆栈展开时,它会再次打印相同的级别。

对于性能和/或内存优化,建议使用循环而不是递归。

于 2012-09-25T06:54:53.163 回答
3
<?php
function drawPyramid($length) {
    for ($i = 1; $i <= $length; ++$i) {
        echo str_repeat("x", $i) . "\n";
    }
    for ($i = $length - 1; $i > 0; --$i) {
        echo str_repeat("x", $i) . "\n";
    }
}

drawPyramid(3);
echo "\n";
drawPyramid(5);
于 2012-09-25T06:50:00.170 回答
2

这是一个递归解决方案,完全摆脱了 for 循环:

function addLevel(&$array, $currentDepth, $maxDepth)
{
    $array[] = str_repeat('*', $currentDepth);
    if($currentDepth < $maxDepth)
    {
        addLevel($array, $currentDepth + 1, $maxDepth);
        $array[] = str_repeat('*', $currentDepth);
    }
}

$R= array();

addLevel($R, 1, 5);

print '<pre>'.implode( "\n",$R ).'</pre>';

It's not exactly neat, that the thing has 3 parameters, but without a class to do this, you would need to use global variables, which is even worse.

于 2012-09-25T06:55:48.590 回答
2

Nice homework assignment. Nice seeing all the different examples.

How about a 1-liner?

for ($i=1; $i<$loops*2; $i++) echo str_repeat('*',($i > $loops ? ($loops * 2) - $i : $i)) . '<br>';
于 2012-09-25T07:21:41.537 回答
2

Examples

echo "<pre>";
echo drawOutput(5, "x");
echo drawOutput(5, "x ");
echo drawOutput(5, "x ", " "); // left padding
echo drawOutput(5, "@-^-@ ", " "); // left padding

Output

x
xx
xxx
xxxx
xxxxx                          <----------------- what you want 
xxxx
xxx
xx
x


x 
x x 
x x x 
x x x x 
x x x x x                      <----------------- Space it out
x x x x 
x x x 
x x 
x 


    x 
   x x 
  x x x 
 x x x x 
x x x x x                      <----------------- Add some padding
 x x x x 
  x x x 
   x x 
    x 



    @-^-@ 
   @-^-@ @-^-@ 
  @-^-@ @-^-@ @-^-@ 
 @-^-@ @-^-@ @-^-@ @-^-@ 
@-^-@ @-^-@ @-^-@ @-^-@ @-^-@ 
 @-^-@ @-^-@ @-^-@ @-^-@ 
  @-^-@ @-^-@ @-^-@ 
   @-^-@ @-^-@ 
    @-^-@ 

Function Used

function drawOutput($length, $str = "* ", $lpad = null) {
    $x = array();
    for($n = $i = $length; $i >= 0; $i --) {
        $x[] = ($lpad ? str_repeat($lpad, $i) : null) . str_repeat($str, $n - $i) . "\n";
    }
    return implode($x) . implode(array_slice(array_reverse($x), 1));
}
于 2013-01-09T16:46:48.230 回答