Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyramid Number Algorithm

I want to generate a static pyramid like these:

1 2 4 8 16 32 64 128 64 32 16 8 4 2 1 
    1 2 4 8 16 32 64 32 16 8 4 2 1 
      1 2 4 8 16 32 16 8 4 2 1 
         1 2 4 8 16 8 4 2 1 
           1 2 4 8 4 2 1 
             1 2 4 2 1 
               1 2 1
                 1

with PHP, I already create this code :

<center>
<?php
    $x1 = 1; $x2 = 128;
    $str_tmp = "";
    $cek = 0;
    $start = 0;
    for($i=0;$i<=7;$i++){
        for($j=$i;$j<=13;$j++){
            for($z=$i;$z<$i;$z++){
            $str_tmp.= ("&nbsp") ;          
            }
            if($x2==1){
                $str_tmp.= $x2;
                break;
            }
            if($cek==0){
                $str_tmp.= $x1 . " ";
                $x1 = $x1 * 2;
                if($x1==$x2){
                    $cek = 1;
                    $x2 = $x2/2;                        
                }
            }if($cek==1){
                $str_tmp.= $x1 . " ";
                $x1 = $x1 /2;
            }if($cek==1&&$x1<1){
            break;
            }
        }
        echo $str_tmp."</br>";
        $str_tmp = "";
        $x1 = 1;
        $cek = 0;       
    }
?>
</center>

I think it's looks like too complicated. Do you guys have a better solution? I don't mind if you guys write the code with another language.

Thank You

like image 391
Yosua Subari Avatar asked Nov 23 '25 01:11

Yosua Subari


2 Answers

Something like this?

echo "<div style=\"text-align: center;\">";

for ($l=7; $l>=0; $l--){

  $str = ""; 

  for ($p=-$l; $p<=$l; $p++)
    $str .= (1 << ($l - abs($p))) . " ";

  echo substr($str,0,-1) . ($l ? "<br>" : "");
}

echo "</div>";
like image 120
גלעד ברקן Avatar answered Nov 24 '25 13:11

גלעד ברקן


Not as nicely formatted (no whitespace to center lines), but it works.

<?php
function pyramid($highest) {
    $pyramid = array();
    while($highest >= 1) {
        $pyramid[$highest] = array();
        $x = $highest;
        $tmp = array();
        while($x >= 1) {
            array_push($tmp, $x);
            $x = intval($x/2);
        }
        $line = array_reverse($tmp); 
        foreach(array_slice($tmp, 1) as $y) {
            array_push($line, $y);
        }
        array_push($pyramid, $line);
        $highest = intval($highest/2);
    }
    return $pyramid;
}


foreach(pyramid(128) as $line) {
    foreach($line as $num) {
        echo $num." ";
    }
    echo "<br>";
}
?>
like image 34
Hexaholic Avatar answered Nov 24 '25 14:11

Hexaholic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!