金字塔数算法
Pyramid Number Algorithm
我想生成这样的静态金字塔:
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, 我已经创建了这个代码:
<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.= (" ") ;
}
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>
我觉得它看起来太复杂了。你们有更好的解决方案吗?我不介意你们用另一种语言编写代码。
谢谢
格式不太好(中心线没有空格),但它有效。
<?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>";
}
?>
是这样的吗?
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>";
我想生成这样的静态金字塔:
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, 我已经创建了这个代码:
<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.= (" ") ;
}
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>
我觉得它看起来太复杂了。你们有更好的解决方案吗?我不介意你们用另一种语言编写代码。
谢谢
格式不太好(中心线没有空格),但它有效。
<?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>";
}
?>
是这样的吗?
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>";