I have a program that prints the star pattern.
Starr Pattern is:
*
*
*
*
* * * * * * * * *
*
*
*
*
My code is:
$n=5;
for($i=0; $i<$n; $i++){
for($k=$n-$i; $k>0; $k--){
echo ' '.' ';
}
for($j=0; $j< ($tot = $i+1); $j++){
if($i==$j && $tot<$n){
echo '* ';
}else{
if($tot<$n){
echo ' '.' ';
}else{
echo '* ';
}
}
}
if($i == ($n-1)){
for($l=$n-1; $l>0;$l--){
echo '* ';
}
}
echo '<br/>';
}
for($i=0;$i<$n;$i++){
for($k=$n-$i; $k>0; $k--){
echo ' '.' ';
}
for($j=0; $j< ($tot = $i+1); $j++){
if($i==$j && $tot<$n){
echo '* ';
}else{
echo ' '.' ';
}
}
echo '<br/>';
}
My question is that how can I calculate the complexity of this code?
And also Is there a good way to reduce loops?
+
to me, guess it's just semantics.... \$\endgroup\$good way to reduce loops
yesstr_repeat
andchunk_split
you can see this example (a code golf answer I did) of what you can do with these 2, codegolf.stackexchange.com/questions/171679/… basically you could make one long string with the space or*
by using str_repeat and then split it into rows with chunk_split \$\endgroup\$function f($n){$s='';$b=str_pad('*',($m=$n*2+1),' ',2);for($i=0;$i<$m;++$i)$s.=($i==$n)?str_repeat('*',$m):$b;return chunk_split($s, $m);}
Sandbox \$\endgroup\$