Print pattern of increasing asterisks and zeros - php

How to print this Pattern?
$number = 5;
for ($i=1; $i <= $number ; $i++) {
for ($j=$i; $j >= 1;$j--){
echo "0";
}
echo "\n";
}
Prints
0
00
000
0000
00000
I've tries like this, but i'm confused to print star and Zero char
for ($i=1; $i <= $number ; $i++) {
$sum = 0;
for ($j=$i; $j >= 1;$j--){
$sum +=$j;
}
echo $i ." => " .$sum ."\n";
}
Prints
1 => 1
2 => 3
3 => 6
4 => 10
5 => 15

You can use str_repeat to generate the strings of required length. Note that for triangular numbers (1, 3, 6, 10, 15, ...) you can generate the i'th number as i(i+1)/2:
$number = 5;
for ($i = 1; $i <= $number; $i++) {
echo str_repeat('*', $i * ($i + 1) /2) . str_repeat('0', $i) . PHP_EOL;
}
Output:
*0
***00
******000
**********0000
***************00000
Demo on 3v4l.org
For a more literal generation of the triangular part of the output (i.e. sum of the numbers from 1 to i), you could use this code which adds $i *'s and 1 0 to the output on each iteration:
$line = '';
$number = 5;
for ($i = 1; $i <= $number; $i++) {
$line = str_repeat('*', $i) . $line . '0';
echo $line . PHP_EOL;
}
Output:
*0
***00
******000
**********0000
***************00000
Demo on 3v4l.org

Here is another way, which uses a more literal reading of the replacement logic. Here, I form each subsequent line by taking the previous line, and adding the line number amount of * to the * section, and then just tag on a new trailing zero.
$line = "*0";
$max = 5;
$counter = 1;
do {
echo $line . "\n";
$line = preg_replace("/(\*+)/", "\\1" . str_repeat("*", ++$counter), $line) . "0";
} while ($counter <= $max);
This prints:
*0
***00
******000
**********0000
***************00000

The number of zeros are equal to $i in the for loop. So we just need to calculate the number of stars and then simply do a str_repeat
$count = 5;
for ($i=1; $i <= $count; $i++) {
$stars = 0;
for($j=1; $j <= $i; $j++) {
$stars = $stars + $j;
}
echo str_repeat('*', $stars).str_repeat('0', $i)."\n";
}
Output:
*0
***00
******000
**********0000
***************00000

$line = '';
for ($i = 1; $i <= 5; $i++) {
$line = str_repeat('*', $i) . $line . '0'; // **str_repeat()** --> getting string length
echo $line . PHP_EOL; // **PHP_EOL** ---> represents the endline character.
}

Related

php reverse half pyramid numbers (special)

How do i display php numbers like so?
1
21
321
4321
54321
654321
right now my code is like this and displays the following.
for ($i = 0; $i <= 5; $i++) {
for ($j = 5; $j > $i; $j--)
{ echo " ";
}
for ($l = 0; $l < $j; $l++){
}
for ($k = 1; $k <= $l; $k++) {
echo "$k";
}
echo "</br>";
}
Basically this shows the correct way of the pattern but does not the correct numbers in order.
1
12
123
1234
12345
The code seems to have too many loops, and can use str_repeat to simplify the logic and loop structure. The counter was dependent on another loop, and thus couldn't be easily changed. I have refactored it into the following:
$printOut = "";
$count = 5;
for ($i = 1; $i <= $count; $i++) {
$printOut = $i . $printOut;
echo str_repeat(" ", $count - $i) . $printOut;
echo "</br>";
}
Output:
1
21
321
4321
54321

How to achieve this number pattern with n input

I want to give n as a input and get a pattern like this.
pattern If n = 4
1
222
33333
4444444
33333
222
1
What is the perfect way to achieve this?
I have tried. But my code is not good! Is there any way to do this with less and clear code!?
echo '<pre>';
$n=4;
for ($i=1; $i <= $n*2-1; $i++) {
if($n<$i){ //bottom part
$scount=$i-$n;
$iterator = 0;
while($iterator != $scount){
$iterator++;
echo ' ';
}
$num = ($n*2)-$i;
$loop = $num*2-1;
$iterator = 0;
while($iterator != $loop){
$iterator++;
echo $num;
}
}elseif ($n==$i){ // middle part
$loop = $i*2-1;
$iterator = 0;
while ($iterator != $loop) {
$iterator++;
echo $i;
}
}else{ //top part
$scount = $n-$i;
$iterator=0;
while ($iterator != $scount) {
$iterator++;
echo ' ';
}
$loop = $i*2-1;
$iterator = 0;
while($iterator != $loop){
$iterator++;
echo $i;
}
}
echo "<br>";
}
?>````
On a similar line to the other answers, but this builds a string with the output. This allows it to build each of the repeating lines in the loop and add it to the start and end of the result string. This means the loop is only run $n-1 times (plus the first line which sets the middle line)...
$n=4;
$output = str_repeat("$n", (2*$n)-1).PHP_EOL;
for ( $i = $n-1; $i>0; $i-- ) {
$line = str_repeat(' ', $n-$i).str_repeat("$i", (2*$i)-1);
$output = $line.PHP_EOL.$output.$line.PHP_EOL;
}
echo $output;
Two for loops which repeats the number of spaces needed and characters.
$n = 4;
for($i=1;$i<=$n;$i++){
echo str_repeat(" ", $n-$i+1) . str_repeat($i, $i*2-1) . "\n";
}
for($i=$n-1;$i>0;$i--){
echo str_repeat(" ", $n-$i+1) . str_repeat($i, $i*2-1) . "\n";
}
https://3v4l.org/1hK3s
You can solve this by noticing the longest line is the one with the max value of n, and that has 2*n-1 n's in it. All other lines need spacing to make them line up with that one which will be half the difference between the number of n's on that line and the number on the longest line. str_repeat is a good way of generating those repeated strings:
echo "<pre>\n";
$n=4;
$max_length = $n * 2 - 1;
for ($i = 1; $i <= $n * 2 - 1; $i++) {
$this_n = ($i <= $n) ? $i : $n * 2 - $i;
$num_ns = $this_n * 2 - 1;
echo str_repeat(' ', ($max_length - $num_ns) / 2);
echo str_repeat("$this_n", $num_ns);
echo "\n";
}
echo '</pre>';
Output:
<pre>
1
222
33333
4444444
33333
222
1
</pre>
Demo on 3v4l.org

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)

Make pattern of asterisks and zeros in increasing lengths

I'm trying to echo stars and zero like the pattern below
*
***0
******00
**********000
The length of the asterisks grows by an increasing factor (in a ballooning fashion) -- the previous number of asterisks plus the current iteration number.
iteration 1: 1 (0 + 1)
iteration 2: 3 (1 + 2)
iteration 3: 6 (3 + 3)
iteration 4: 10 (6 + 4)
iteration 5: 15 (10 + 5)
etc
The length of the zeros increases by a static factor.
iteration 1: 0
iteration 2: 1
iteration 3: 2
iteration 4: 3
iteration 5: 4
etc
My code currently looks like this:
for ($i=0; $i<=10; $i++)
{
echo "*";
for ($j=0; $j<$i; $j++)
{
echo "*";
}
for ($z=0; $z<$i; $z++)
{
echo "0";
}
echo "</br>";
}
However I'm getting this result:
*
**0
***00
****000
*****0000
******00000
The number of stars is indicated by triangle numbers, 1, 1+2, 1+2+3. You want to increment your inner loop max value by $i with every iteration:
$k = 0;
for ($i=1; $i<=10; $i++)
{
$k += $i;
for ($j=1; $j<=$k; $j++)
{
echo "*";
}
...
}
This is also a good case where your loops should be initialized with 1 rather than 0, because it is more intuitive. 0-based loops work best when you are working with arrays.
I think something like this is more efficient; you can cache the current sequence of stars and zeros.
$cache_star = "";
$cache_zero = "";
for ($i=1; $i<=10; $i++)
{
for ($j=1; $j<=$i; $j++)
{
$cache_star .= "*";
}
echo $cache_star.$cache_zero;
$cache_zero .= "0";
}
Here's what I got:
for($i = 1; $i != 5; $i++)
{
$triangle = (0.5 * $i) * ($i + 1);
echo str_repeat('*', $triangle) . str_repeat('0', $i) . PHP_EOL;
}
Uses the formula 0.5n(n + 1) - the triangle numbers formula.
Example output:
*0
***00
******000
**********0000
I quite like #jordandoyle's approach, but I correct the zeros pattern by subtracting 1 from $i in the second str_replace()..
Code: (Demo)
$number = 5;
for ($i = 1; $i <= $number; ++$i) {
echo str_repeat('*', $i * .5 * ($i + 1))
. str_repeat('0', $i - 1)
. PHP_EOL;
}
Output:
*
***0
******00
**********000
***************0000
If this answer lacks significant uniqueness versus an earlier answer, I'll include a recursive approach as well (instead of a classic loop).
Code: (Demo)
function printLines($i, $lines = [], $newline = PHP_EOL) {
if ($i > 0) {
array_unshift(
$lines,
str_repeat('*', $i * .5 * ($i + 1))
. str_repeat('0', $i - 1)
);
printLines(--$i, $lines);
} else {
echo implode($newline, $lines);
}
}
printLines(5);
You can even copy the previous line and insert it into the middle of the next line to form the desired pattern. This is the functional-style equivalent of #CoertMetz's nested loop technique.
Code: (Demo)
$number = 5;
$line = '';
for ($i = 1; $i <= $number; ++$i) {
echo (
$line = str_repeat('*', $i)
. $line
. ($i > 1 ? '0' : '')
)
. PHP_EOL;
}
All above techniques deliver the same result.
Smells like homework... But ok, what about this:
$star = "*";
echo $star."\n";
for ($i=0; $i<=10; $i++)
{
$star = $star."**";
echo $star;
echo str_repeat("0", $i+1);
echo "\n";
}
Outcome:
*
***0
*****00
*******000
*********0000
***********00000
*************000000
***************0000000
*****************00000000
*******************000000000
*********************0000000000
***********************00000000000
Demo:
http://sandbox.onlinephpfunctions.com/code/583644f782005adb9e018b965cbbdefaf63c7c79

Calculate a specific number PHP

I have a for loop, where $i is 0, and it will run until $i reaches 4. I am trying to make a code that would output numbers in an order like this: 01, 11, 02, 12, 03, 13... etc... Now, the thing is next: when $i is 1, the script should make an order of those number in the boundaries of 1 and 20. When $i is 2, it would be 21 to 40, etc.
I've tried many things (mostly deleted), could not come up with anything that would work the right way.
The inner loop:
for ($j = 0; $j != 10; ++$j)
{
echo $j + 1 + 10 * ($i - 1);
echo $j + 1 + 10 * $i;
}
Try this piece of code;
<?php
$num = 4;
for($i=1;$i<($num + 1);$i++){
$string = "0" . $i . ", 1" . $i;
if($i<$num){
$string .= ", ";
}
echo $string;
}
?>
printf will format your numbers with a leading zero, as specified:
<?php
$format = "%02d ";
for ($i = 1; $i <= 4; $i++) {
$k = 2 * $i - 1;
for ($j = 1; $j <= 10; $j++) {
printf($format, ($k - 1) * 10 + $j);
printf($format, $k * 10 + $j);
}
echo "<br />";
}
?>
You can try:
<?php
$ten = 10;
for ($i = 0; $i<=4; ++$i)
{
echo "0".$i." , ";
echo $ten + $i."<br/>";
}
?>
Only change the range of $i
Thanks

Categories