Wild Widow
Wild Widow

Reputation: 2549

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?

Upvotes: 2

Views: 8433

Answers (15)

vrnair24
vrnair24

Reputation: 93

<?php
    
    
    class StairsOrPyramid{
        
        const BLOCKS = 10;
        
        function leftAllignedPyramid(){
            
            for($i=0 ; $i < self::BLOCKS; $i++){
                for($j=0;$j <= $i;$j++){
                    print("*");
                }
                print("\n");
            }
        }
        
        function rightAllignedPyramid(){
            
            for($i=self::BLOCKS; $i>0; $i--){
                for($j=1; $j <= self::BLOCKS; $j++){
                    $j < $i ? print(" "):print("*");
                }
                print("\n");
            }
            
        }
        
    }
    
    
    $stairs = new StairsOrPyramid();
    $stairs->leftAllignedPyramid();
    
    $stairs->rightAllignedPyramid();

Upvotes: 0

Thisaru
Thisaru

Reputation: 301

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";
    }
}

Upvotes: 0

Kasun Hasanga
Kasun Hasanga

Reputation: 1945

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";
}

Upvotes: 0

mackelele
mackelele

Reputation: 129

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 "&nbsp;" 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";
    }
  }

Upvotes: 0

Desire Kaleba
Desire Kaleba

Reputation: 1312

  1. Check if n is between 0 and 101 ( 0 < n <= 100)
  2. Loop through each row 2.1 print spaces according to the last item position 2.2 print the items
  3. 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

     #
    ##
   ###
  ####
 #####
######

Upvotes: 0

RodYokoo
RodYokoo

Reputation: 11

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";
        } 
    }  
}

Upvotes: 1

Artee
Artee

Reputation: 834

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

Upvotes: 0

Ion Gorincioi
Ion Gorincioi

Reputation: 581

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)

Upvotes: -1

Bhavin Visariya
Bhavin Visariya

Reputation: 71

//PHP

$n = 6;  // Number of rows.
for($i=1;$i<=$n;$i++){
    echo str_repeat(' ', $n-$i) . str_repeat('#', $i);
    echo '\n';
}

Upvotes: 2

XFaramir
XFaramir

Reputation: 41

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";

}

?>

Upvotes: 0

A. Sharma
A. Sharma

Reputation: 56

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";
}

Upvotes: 3

Ashish
Ashish

Reputation: 643

$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>';
}

Upvotes: 0

Ruhi Kuzu
Ruhi Kuzu

Reputation: 1

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

Upvotes: 0

Ishu nanda
Ishu nanda

Reputation: 19

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);
}

Upvotes: 0

Łukasz Jakutowicz
Łukasz Jakutowicz

Reputation: 1

Use print(' '), if you want to go to next line put print(' ')."\n"

Upvotes: -1

Related Questions