This article describes the example of php printing a solid and hollow rhombus with side length N method. Share it with everyone for your reference. The specific analysis is as follows:
Solid diamond calculation method:
$n: side length
$i: current line, starting from 0
$rows: Total number of rows
Upper part
Number of preceding spaces =$n-$i-1
Number of characters=$i*2+1
Lower part
Number of spaces in front =$i-$n+1
Number of characters=($rows-$i)*2-1
Use str_pad to reduce for/while loops
Copy code The code is as follows:/**
* Print solid diamond
* @param int $n side length, default 5
* @param String $s characters displayed, default*
* @return String
*/
function solidDiamond($n=5, $s='*'){
$str = '';
// Calculate the total number of rows
$rows = $n*2-1;
// Loop to calculate the * of each row
for($i=0; $i<$rows; $i++){
If($i<$n){ // Upper part
$str .= str_pad('', ($n-$i-1), ' '). str_pad('', $i*2+1, $s)."rn";
} Else {// lower part
$str .= str_pad('', ($i-$n+1), ' '). str_pad('', ($rows-$i)*2-1, $s). "rn";
}
Return $str;
}
echo '
Copy code The code is as follows: *
***
*****
*******
*********
*******
*****
***
*
$n: side length
$i: current line, starting from 0
$rows: Total number of rows
Number of preceding spaces =$n-$i-1
Number of empty spaces =$i*2+1-2
Number of characters = $i*2+1 - number of empty spaces
Number of preceding spaces =$i-$n+1
Number of empty spaces = ($rows-$i)*2-1-2
Number of characters = ($rows-$i)*2-1 - Number of empty spaces
Copy code The code is as follows: /**
* Print hollow diamond
* @param int $n side length, default 5
* @param String $s characters displayed, default*
* @return String
*/
function hollowDiamond($n=5, $s='*'){
$str = '';
// Calculate the total number of rows
$rows = $n*2-1;
// Loop to calculate the * of each row
for($i=0; $i<$rows; $i++){
If($i<$n){ // Upper part
$tmp = $i*2+1;
$str .= str_pad('', ($n-$i-1), ' '). str_pad(str_pad('', $tmp-2, ' ', STR_PAD_BOTH), $tmp, $s, STR_PAD_BOTH). "rn";
} Else {// lower part
$tmp = ($rows-$i)*2-1;
$str .= str_pad('', ($i-$n+1), ' '). str_pad(str_pad('', $tmp-2, ' ', STR_PAD_BOTH), $tmp, $s, STR_PAD_BOTH). "rn";
}
Return $str;
}
echo '
Copy code The code is as follows: *
* *
* * *
* * *
* * *
* * *
* * *
* *
*
I hope this article will be helpful to everyone’s PHP programming design.