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)
Related
Write a PHP code to print following number pattern:
147
258
369
I am trying like this but its shows me shows below. how to convert column to row pattern.
<?php
$num = "";
for($i=1;$i<=9;$i++) {
$num .= $i;
if($i%3==0){
$num .="<br />";
}
}
echo $num;
?>
please help me
You need to use for loop inside for loop to achieve this. Below is the code
$num = "";
for( $i = 1; $i <= 3; $i++ ) {
for( $j = 0; $j <= 2; $j++) {
$k = $i + ( $j * 3 );
$num .= $k;
}
$num .= "<br />";
}
echo $num;
Here is another way to get this output.
for($i = 1; $i <= 3; $i++) {
$print = $i;
for($j = 1; $j <= 3; $j++) {
echo $print;
$print = $print + 3;
}
echo "<br />";
}
I run this program, but I need the output within table. So would you please solve this?
<?php
$s="*";
for($b=1; $b<=5; $b++) {
for($c=5; $c>=$b-1; $c--) {
if($c>=$b) {
echo $s;
}
else if($b != 1) {
echo " ";
}
}
for($d=5; $d>=$b; $d--) {
echo $s;
}
echo "<br/>";
}
?>
If you're fine regardless of how the code was written (only results matter), you can use this:
print('<table>');
for ($i = 0; $i < 5; $i++)
{
print('<tr>');
for ($j = 1; $j <= 5; $j++)
{
print('<td>');
(5 - $i >= $j) ? print('*') : '';
print('</td>');
}
for ($j2 = 1; $j2 <= 5; $j2++)
{
print('<td>');
(1 + $i <= $j2) ? print('*') : '';
print('</td>');
}
print('</tr>');
}
print('</table>');
What I did there is I sliced table in half vertically and used 2 for loops to fill left and right halfs. You will get something like this:
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));
I want to print integer in triangle form which look like this
1
121
12321
I tried this but I do not get the actual result
for($i=1;$i<=3;$i++)
{
for($j=3;$j>=$i;$j--)
{
echo " ";
}
for($k=1;$k<=$i;$k++)
{
echo $k;
}
if($i>1)
{
for($m=$i; $m>=1; $m--)
{
echo $m;
}
}
echo "<br>";
}
Output of this code is:
1
1221
123321
Where am I going wrong, please guide me.
Another integer solution:
$n = 9;
print str_pad ("✭",$n," ",STR_PAD_LEFT) . PHP_EOL;
for ($i=0; $i<$n; $i++){
print str_pad ("", $n - $i);
for ($ii=-$i; $ii<=$i; $ii++){
if ($i % 2 != 0 && $ii % 2 == 0)
print "&#" . rand(10025,10059) . ";";
else print $i - abs($ii) + 1;
}
print PHP_EOL;
}
✭
1
1✬1
12321
1❊3✪3✳1
123454321
1✼3✶5❃5❈3✸1
1234567654321
1✾3✯5✿7❉7✫5✷3✶1
12345678987654321
Or if you already have the string, you could do:
$n = 9; $s = "12345678987654321"; $i = 1;
while ($i <= $n)
echo str_pad ("", $n-$i) . substr ($s,0,$i - 1) . substr ($s,-$i++) . PHP_EOL;
Your code should be this:
for($i=1;$i<=3;$i++)
{
for($j=3;$j>$i;$j--)
{
echo " ";
}
for($k=1;$k<$i;$k++) /** removed = sign*/
{
echo $k;
}
if($i>=1) /**added = sign*/
{
for($m=$i; $m>=1; $m--)
{
echo $m;
}
}
echo "<br>";
}
Try this.
Details:
Your loop is not proper as in case of for($k=1;$k<=$i;$k++), this will print the
repeated number when check the condition for less then and again for equals to.
So remove the equals sign.
reason to add the eqaul sign in if($i>=1) is that the first element will not print if there will not be equals as first it will be print by for loop from where removed the equal sign.
Your output will be this:
1
121
12321
For all the x-mas lovers:
$max = 9; # can be 2 .. 9
for($i = 1; $i <= $max; $i++) {
$line = (str_pad('', $max - $i));
for($ii = 1; $ii <= $i; $ii++) {
$line .= $ii;
}
for($ii = $i-1; $ii > 0; $ii--) {
$line .= $ii;
}
echo $line . PHP_EOL;
}
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
Amazing what computers are able to achieve nowadays! Isn't it?
A little late to the party, but here's yet another solution that uses a "for" loop with two initialization variables and a ternary-based incrementer/decrementer. It's an unorthodox use of a "for" loop, but it's still perfectly valid and arguably makes the code more elegant and easier to follow. I chose to add space before and after each semicolon and omit all other space inside the parentheses so it's easier to visualize each of the three pieces of the "for" loop (initialization, condition, increment/decrement):
$count = 9;
echo "<pre>";
for ($i=1; $i<=$count; $i++) {
echo str_pad("",$count-$i," ",STR_PAD_LEFT);
for ( $j=1,$up=true ; $j>0 ; $up?$j++:$j-- ) {
echo $j;
if ($j==$i) {$up = false;}
}
echo "<br>";
}
echo "</pre>";
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
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>