Print pyramid pattern - php

1
1 2 1
1 2 3 2 1
1 2 1
1
$newline = "\r\n";
$prnt = '*';
$nos = 3;
for($i = 1; $i <= 2; $i++)
{
for($s = $nos; $s >= 1; $s--)
{
echo " ";echo " ";echo " ";
}
for($j = 1; $j <= $i; $j++)
{
echo $j;echo " ";
}
$m = 2;
for($k = 1; $k <= ($i - 1); $k++)
{
echo $k;echo " ";
}
echo '<br />';
$nos--;
}
$nos = 1;
for($i = 3; $i >= 1; $i--)
{
for ($s = $nos; $s >= 1; $s--) {
echo " ";echo " ";echo " ";
}
for($j = 1; $j <= $i; $j++)
{
echo $j;echo " ";
}
for($k = 1; $k <= ($i - 1); $k++)
{
echo $k;echo " ";
}
$nos++;
echo '<br />';//printf("\n");
}
i got output
1
1 2 1
1 2 3 1 2
1 2 1
1
am not able to print space when i use echo ' '; so i used echo " "; but i dont want to use echo " "; plz resolve this issue.
I am having problem creating above program but somewhere missing a value may be need apply some condition over there . Please see my code.

Printing multiple spaces in straight HTML isn't allowed because of how it must be rendered.
If you want to print exactly - whitespaces included - just wrap your code with a <pre/> tag.
<pre>Spacing will be literal.</pre>
You could also format with the white-space CSS property by setting it to pre.
.spaces {
white-space: pre;
}
<div class="spaces">Spacing will be literal.</div>

This is a fun little algorithm. Here's a recursive solution in PHP. I wrap it in <PRE> tag so that I can use spaces and new lines "\n".
<pre>
<?php
function printPyramid($height) {
// initialize
$size = ($height * 2) - 1;
$half = $size / 2;
$arr = Array();
for($r = 0; $r < $size; $r++) {
$arr[] = array();
for($c = 0; $c < $size; $c++) {
$arr[$r][] = "";
}
}
$arr[$half][$half] = $height;
// recursively build, pass array as reference "&"
pyramidRec($arr, $half, $half, $size);
// print
for($r = 0; $r < $size; $r++) {
for($c = 0; $c < $size; $c++) {
if(empty($arr[$r][$c]))
echo " ";
else if(strlen($arr[$r][$c]) == 1)
echo "{$arr[$r][$c]} ";
else
echo $arr[$r][$c];
}
echo "\n";
}
}
function pyramidRec(&$arr, $r, $c, $size) {
$val = $arr[$r][$c];
$newVal = $val - 1;
if($newVal == 0)
return;
// up
if($r - 1 >= 0 && empty($arr[$r-1][$c])) {
$arr[$r-1][$c] = $newVal;
pyramidRec($arr, $r-1, $c, $size);
}
// down
if($r + 1 < $size && empty($arr[$r+1][$c])) {
$arr[$r+1][$c] = $newVal;
pyramidRec($arr, $r+1, $c, $size);
}
// left
if($c - 1 >= 0 && empty($arr[$r][$c-1])) {
$arr[$r][$c-1] = $newVal;
pyramidRec($arr, $r, $c-1, $size);
}
// right
if($c + 1 < $size && empty($arr[$r][$c+1])) {
$arr[$r][$c+1] = $newVal;
pyramidRec($arr, $r, $c+1, $size);
}
}
printPyramid(5);
?>
</pre>

Related

Display the pattern in which the first and a last number of each row will be 1

I am trying to use for loops to make a shape that looks like the diamond shape .
<?php
for($i=0;$i<=9;$i++){
for ($d=10-$i; $d > 0; $d--) {
echo " ";
}
for($j=1;$j<=$i;$j++){
echo " ".$i." ";
}
echo "<br>";
}
for($i=8;$i>=1;$i--){
for ($d=0; $d <= 9-$i; $d++) {
echo " ";
}
for($j=$i;$j>=1;$j--){
echo " ".$i." ";
}
echo "<br>";
}
?>
What it looks like :
What I desire :
I need a help in this.
Thank you
I'll post this here because I had fun making this. Felt like learning the basics again.
<?php
$max_size = 9;
function createSpaces($n){
$spaces = '';
for($i = 0; $i < $n; $i++){
$spaces .= ' '; //change to ' ' for HTML
}
return $spaces;
}
function createRows($i, $max_size){
$row = '';
$row .= createSpaces($max_size - $i);
for($j = 1; $j <= ($i-1); $j++){
$row .= $j;
}
for($k = $i; $k >= 1; $k--){
$row .= $k;
}
$row .= createSpaces($max_size - $i);
echo $row . PHP_EOL; //change PHP_EOL to '<br>' for HTML
}
for($i = 1; $i <= $max_size; $i++)
{
createRows($i, $max_size);
}
for($i = ($max_size - 1); $i >= 1; $i--)
{
createRows($i, $max_size);
}
Javascript version:
var max_size = 9;
function createSpaces(x) {
var spaces = '';
for (var i = 0; i < x; i++) {
spaces += ' ';
}
return spaces;
}
function createRow(i, max_size) {
var row = '';
row += createSpaces(max_size - i);
for (var j = 1; j <= (i - 1); j++) {
row += j;
}
for (var k = i; k >= 1; k--) {
row += k;
}
row += createSpaces(max_size - i);
document.write(row + '<br>');
}
for (var i = 1; i <= max_size; i++) {
createRow(i, max_size)
}
for (var i = (max_size - 1); i >= 1; i--) {
createRow(i, max_size)
}
<style>
body {
font-family: monospace;
}
</style>
Here is a similar version, where you only need to call the function once.
function diamond($max){
$result = '<p style="text-align:center">';
$last = 0;
for($i=1;$i<=$max;$i++){
for($x=1;$x<=$i;$x++){
$last=$x;
$result .= $last;
}
for($y=$last-1;$y>=1;$y--){
$result .= $y;
}
$result .= "<br />";
}
for($i=$max-1;$i>=1;$i--){
for($x=1;$x<=$i;$x++){
$last=$x;
$result .= $last;
}
for($y=$last-1;$y>=1;$y--){
$result .= $y;
}
$result .= "<br />";
}
$result .= "</p>";
return $result;
}
echo diamond(9);
echo diamond(7);
echo diamond(10);

how to write a nested php loop that draws an image with few lines of code?

How best can i solve this with less code as possible below is the problem
*****
****x
***xx
**xxx
*****
**xxx
***xx
****x
*****
this is my code that i want to improve:
<?php
for ($i=0; $i < 5 ; $i++) {
if($i >= 1 & ($i <= 3))
{
for ($t=0; $t < 5-$i ; $t++)
echo "*";
for ($t=0; $t < $i ; $t++)
echo "x";
}
else
for ($j=0; $j < 5 ; $j++)
echo "*";
echo "<br/>";
}
for ($f=1; $f < 5 ; $f++) {
for ($j=0; $j < $f+1; $j++)
echo "*";
for ($v=3; $v>= $f; $v--)
echo "x";
echo "<br/>";
}
?>
To create string with repeated symbols you can use str_repeat. Using this function your code can be simplified to:
$num = 5;
for ($i = $num; $i > 1; $i--) {
echo str_repeat('*', $i) . str_repeat('x', $num - $i) . PHP_EOL;
}
echo str_repeat('*', $num) . PHP_EOL;
for ($i = 2; $i <= $num; $i++) {
echo str_repeat('*', $i) . str_repeat('x', $num - $i) . PHP_EOL;
}
Even if you cannot use php core functions, you can write you own function to create same results as str_repeat:
function createLine($starsCount, $XCount) {
$result = '';
for ($i = 0; $i < $starsCount; $i++) {
$result .= '*';
}
for ($i = 0; $i < $XCount; $i++) {
$result .= 'x';
}
return $result;
}
And rewrite code as:
$num = 5;
for ($i = $num; $i > 1; $i--) {
echo createLine($i, $num - $i) . PHP_EOL;
}
echo createLine($num, 0) . PHP_EOL;
for ($i = 2; $i <= $num; $i++) {
echo createLine($i, $num - $i) . PHP_EOL;
}

Hackerrank draw a staircase of length N in php

Draw a staircase of height N like this:
#
##
###
####
#####
######
Staircase of height 6, note the last line should have zero spaces.
My solution does not work correctly
function draw($size)
{
for ($i = 1; $i <=$size ; $i++)
{
$spaces = $size-$i;
while ($spaces)
{
echo " ";
$spaces--;
}
$stairs = 0;
while ($stairs < $i)
{
echo "#";
$stairs++;
}
echo "<br/>";
}
}
draw(6);
//output
#
##
###
####
#####
######
It is not printing the spaces, I tried \n, PHP.EOL still it didn't work. Any suggestions?
Although other solutions are all good , here is my code as well.
$max=5;
for ( $i =1 ; $i<=$max;$i++) {
for ( $space = 1; $space <= ($max-$i);$space++) {
echo " ";
}
for ( $hash = 1; $hash <= $i;$hash ++ ) {
echo "#";
}
echo "\n";
}
//PHP
$n = 6; // Number of rows.
for($i=1;$i<=$n;$i++){
echo str_repeat(' ', $n-$i) . str_repeat('#', $i);
echo '\n';
}
for(var i = 0; i < n; i++)
{
var s = "";
for(var j = 0; j < n; j++)
{
if(n - i - 2 < j)
{
s += "#";
}
else
{
s += " ";
}
}
console.log(s);
}
for ($i=0; $i<$n; $i++){
for ($j=0; $j<$n; $j++){
if($i+$j>$n-2){
echo "#";
} else {
echo " ";
}
if($j==$n-1 && $i+$j<$n*2-2){ //The second part is to dont break the last line
echo "\n";
}
}
}
Here's another solution:
$int = 7;
for($i = 1; $i<=$int; $i++){
printf('%1$s%2$s%3$s',str_repeat(" ",$int-$i),str_repeat("#",$i),"\n");
}
From official PHP documentation:
str_repeat
$n = 6;
for ($i = 0; $i < $n; $i++) {
$pad = 1;
for ($space = 0; $space < $n-$i-1; $space++) {
$pad++;
}
echo str_pad('#', $pad,' ',STR_PAD_LEFT);
for ($j = 0; $j < $i; $j++) {
echo '#';
}
echo '<br>';
}
Took me a while but finally I manage to do it following OFC (A. Sharma) Example.
<?php
$handle = fopen("php://stdin","r");
$n = intval(fgets($handle));
for ($rows = 0; $rows < $n; $rows++) {
for ($columns = 0; $columns < $n - $rows - 1; $columns++) {
echo " ";
}
for ($columns = 0; $columns < $rows + 1; $columns++) {
echo "#";
}
echo "\n";
}
?>
Use PHP functions range() and str_repeat() for an elegant solution:
function staircase($n){
foreach (range(1, $n) as $i)
print( str_repeat(' ',$n-$i).str_repeat('#',$i)."\n");
}
demo
Check if n is between 0 and 101 ( 0 < n <= 100)
Loop through each row
2.1 print spaces according to the last item position
2.2 print the items
Separate rows
The code below explains everything...
function staircase($n) {
// check if n is between 0 and 101 (0 < n <=100)
if( 0 < $n && $n > 100 ) {
} else {
// Loop through each row
for($i = 1; $i <= $n; $i++) {
// print spaces according to the last item position
$si = 1;
while( $si <= ($n - $i)){
print(" ");
$si++;
}
// print the items
for($j = 1; $j <= $i; $j++) {
print("#");
}
// separate rows
print("\n");
}
}
}
Output: For n = 6
#
##
###
####
#####
######
After playing around with the code and trying/failing couple of times I finally got it right. Notice how in order to print the space and new line I am using "\n". Previous "<br/>" and " " for space didn't work.
Break line will come out of the loop every row number. So if we have $n=4 then every 4 spaces after break line will be echoed.
I have made 2 loops to fill in all fields in the staircase.
The tricky part here is to have them right aligned. This is where if statement comes in place.
Reference link:
Hackerrank Challenge
// Complete the staircase function below.
function staircase($n) {
for($i=1; $i<=$n; $i++){
for($j=1; $j <= $n; $j++){
if( ($n - $i) < $j ){
echo "#";
}else{
echo " ";
}
}
echo "\n";
}
}
Try This
$n=6;
for($i=1;$i<=$n;$i++){
for($spaces=1;$spaces<=($n-$i);$spaces++){
echo " ";
}
for($staires=0;$staires<$i;$staires++){
echo "#";
}
echo "\n";
}
This worked for me
$n = 6;
function staircase($n) {
for($i=1; $i <= $n; $i++){
for($j=1; $j <= $n; $j++){
if($j > $n-$i){
echo "#";
}else{
echo " ";
}
}
echo "\n";
}
}
Use print(' '), if you want to go to next line put print(' ')."\n"
JavaScript:
Solution:
function StairCase(n){
let x = [];
for(let i = 0; i<n; i++){
while(x.length < n){
x.push(" ");
}
x.shift();
x.push("#");
console.log(x.join(''));
} } //StairCase(6)

How to do nested loop in descending order?

What I want to get with for loop. Something will be like this.
*
**
***
****
*****
****
***
**
*
This thing I want to create right now I have this code.
<?php
$i = 1;
$end = 5;
$star = "*";
for($i; $i <= $end; $i++){
for($b=1; $b <= $i; $b++){
echo $star;
}
if($i == $end){
for($c=1; $c <= $end; $c++ ){
for($d=i; $d >= 2; $d--){
echo $star;
}
echo "<br>";
}
}
};
?>
And it's working fine with
*
**
***
****
*****
But then I need opposite loop first 4 then 3 then 2 then 1...
Where am I going wrong with this?
Just for fun. Try this:
$stars = 1;
for ($i = 0; $i < 9; $i++) {
for ($s = 1; $s <= $stars; $s++) {
echo "*";
}
echo "\n";
$stars += ($i<4)?1:-1;
}
And, for even more fun, one with just one for loop:
$stars = 0;
$starctr = 0;
for ($i = 0; $i < 25; $i++) {
echo "*";
if ($stars == $starctr) {
echo "\n";
$stars += ($i<14)?1:-1;
$starctr = 0;
} else {
$starctr++;
}
}
Can using nested for loop. Example:
$n = 5;
for($i = 1; $i <= $n; $i++){
for($j = 1; $j <= $i; $j++){
echo '*';
}
echo '<br />';
}
for($i = $n-1; $i >= 1; $i--){
for($j = $i; $j >= 1; $j--){
echo '*';
}
echo '<br />';
}
Another technique using array_fill(), array_map(), array_reverse()
$n = 5; $arr = array();
for($i = 1; $i <= $n; $i++){
$arr[] = array_fill(0, $i, '*');
}
array_map(function($v){echo join('', $v) . '</br>';},$arr);
unset($arr[count($arr) - 1]); //remove last index value
array_map(function($v){echo join('', $v) . '</br>';},array_reverse($arr));
<?php
for($i=0;$i<=6;$i++){
for($k=6;$k>=$i;$k--){
echo " ";
}
for($j=1;$j<=$i;$j++){
echo "* ";
}
echo "<br>";
}
for($i=5;$i>=1;$i--){
for($k=6;$k>=$i;$k--){
echo " ";
}
for($j=1;$j<=$i;$j++){
echo "* ";
}
echo "<br>";
}
?>
This can be achieved with only 2 for loops.
$offset = 1;
for ($i = 1; $i > 0; $i += $offset)
{
for($j = 1; $j <= $i; $j++){
echo '*';
}
echo '<br />';
if ($i === 5)
$offset = -1;
}
<?php
$i = 1;
$end = 5;
$star = "*";
for($i; $i <= $end; $i++){
for($b=1; $b <= $i; $b++){
echo $star;
}
};
for($c=$send; $c>=2; $c-- ){
for($d=$end; $d >= 2; $d--){
echo $star;
}
echo "<br>";
};
?>
Using a single for loop:
$end = 5;
$out = array();
for ($i=0;$i<$end;++$i)
{
$out[] = str_repeat('*', $i+1);
}
echo implode(PHP_EOL, $out).PHP_EOL;
array_pop($out);
$out = array_reverse($out);//remove last ****** <-- only one line with 5 stars
echo implode(PHP_EOL, $out).PHP_EOL;
Replace PHP_EOL with <br> if you want to, but this is the least loopy way to write this code I can think of
live demo
Here's a recursive attempt:
function ladder($n, $counter=1, &$acc=array())
{
if ($counter == ($n*2)) {
return implode($acc);
}
if ($counter <= $n) {
$acc[$counter] = str_repeat('*', $counter) . "\n";
$counter++;
}
if ($counter > $n) {
$diff = (int) $n-$counter;
$acc[$counter] = str_repeat('*', $n+$diff) . "\n";
$counter++;
}
return ladder($n, $counter, $acc);
}
print_r(ladder(5));

print number vertically and grouping it

I am trying to print number vertically and it must be in group
here is my code
$nums = 105;
$rows = 8;
$col = floor($nums / $rows);
$group = floor($col / 3);
$count = 0;
for ($g = 0; $g <= $group; $g++) {
echo "<div class='group'>";
for ($i = 1; $i <= $rows; $i++) {
for ($j = $i; $j <= 24; $j = $j + $rows) {
$count++;
if($count>$nums){
break;
}
echo "<div class='fleft'>$count</div>";
}
echo "<div class='clear'></div>";
}
echo "</div>";
}
out of above
but i want output like for the first column
and next group number will start from where first group number end. in this case next group start from 25
please ask if any doubt
$nums = 105;
$rows = 8;
$colsize = 3;
$col = floor($nums / $rows);
$group = floor($col / $colsize);
$count = 0;
$groupsize = $rows * $colsize;
for ($g = 0; $g <= $group; $g++) {
echo "<div class='group'>";
$modulo = 0;
$correction = 0;
$rest = $nums - $count;
if ($rest < $groupsize) {
$empty = $groupsize - $rest;
$correction = floor($empty / $colsize);
$modulo = $empty % $colsize;
}
for ($i = 1; $i <= $rows; $i++) {
$colind = 0;
for ($j = $i; $j <= $groupsize; $j = $j + $rows) {
$count++;
if ($count > $nums) {
break;
}
$val = $j + ($g * $groupsize);
$val -= $colind * $correction;
$modcor = $colind - ($colsize - $modulo);
if ( $modcor > 0 ) {
$val -= $modcor;
}
echo "<div class='fleft'>" . $val . "</div>";
$colind++;
}
echo "<div class='clear'></div>";
}
echo "</div>";
}
This works:
Also, you can change number of digits, columns or size of column
for($group = 0; $group < 3; $group++){
for($row =1 ; $row <= 8; $row++){
for($col = 0; $col <= 2; $col++){
echo ($group*24)+ $row + 8 * $col; echo " ";
}
echo "\n";
}
}
This code will print the number in the requested format. You need to modify according to your need.
may be i am mad , made a simple alter .... try this
$nums = 105;
$rows = 8;
$col = floor($nums / $rows);
$group = floor($col / 3);
$count = 0;
$letCounter=0; //added a counter
for ($g = 0; $g <= $group; $g++) {
echo "<div class='group'>";
for ($i = 1; $i <= $rows; $i++) {
$letCounter=0; //reset counter on each loop
for ($j = $i; $j <= 24; $j = $j + $rows)
{
$count++;
if($count>$nums)
{break;}
//made an alter in the below line , some math :)
echo "<div class='fleft'>".($letCounter++ * $rows +$i)."</div>";
}
echo "<div class='clear'></div>";
}
echo "</div>";
}
Thanks !
This May work
$nums = 105;
$rows = 8;
$col = floor($nums / $rows);
$group = floor($col / 3);
$count = 0;
$flag = true;
for($c=1;$c<=$col;$c++)
{
if($c%$group== 1)
{
echo "Group Start";
$flag = false;
}
for ($i = 1; $i <= $rows; $i++) {
$count++;
echo "<div class='fleft'>$count</div>";
echo "<div class='clear'></div>";
}
echo "Line End";
if($c%$group == 2&& $flag)// Check here for your requirement
echo "Group End </br>";
$flag = true;
}

Categories