bro yo
bro yo

Reputation: 1

Pascals Diagonal Triangle in PHP

I'm trying to use php code to print out pascals triangle (in the diagonal style like this- http://www.cut-the-knot.org/arithmetic/combinatorics/PascalTriangle.gif)

I tried this code:

<?php

$f = 10;
for ($x = 0; $x <= $f; $x++) {
    echo "1"." ";
    $previous_line[$x]=1;

}

echo "<br>";

for ($x = 0; $x < $f; $x++) {
    echo "1"." ";

for ($y = 1; $y <= $f-$x-1; $y++) {
    $sum = 0;

    for ($z = 0; $z <= $y; $z++) {
        $sum = $sum + $previous_line[$z];
    }
    echo $sum." ";
}
echo "<br>";
}

But I get this output:

1 1 1 1 1 1 1 1 1 1 1 

1 2 3 4 5 6 7 8 9 10 

1 2 3 4 5 6 7 8 9 

1 2 3 4 5 6 7 8 

1 2 3 4 5 6 7 

1 2 3 4 5 6 

1 2 3 4 5 

1 2 3 4 

1 2 3 

1 2 

1 

What am I doing wrong?

Upvotes: 0

Views: 294

Answers (2)

xlordt
xlordt

Reputation: 521

Since Justin beat me to the punch, I though I would post an improved version. Please note that there is probably better ways to do this.

I removed your first loop since it wasn't need, then I moved $previous_line inside the second loop and checked to make sure that it is being set. Last I update $currentSum and assign

$totalToLoop = 10;

for ($x = 0; $x <= $totalToLoop; $x++) {

    $currentSum  = 1;

    echo '1 ';

    for ($y = 1; $y <= ($totalToLoop - $x); $y++) { 

        if (!isset($previous_line[$y])) {

            $previous_line[$y] = 0;
        }

        printf('%d &nbsp;', $currentSum = ($currentSum + $previous_line[$y]));

        $previous_line[$y] = $currentSum;
    }

    echo '<br>';

}

results.

1 1  1  1  1  1  1  1  1  1  1  
1 2  3  4  5  6  7  8  9  10  
1 3  6  10  15  21  28  36  45  
1 4  10  20  35  56  84  120  
1 5  15  35  70  126  210  
1 6  21  56  126  252  
1 7  28  84  210  
1 8  36  120  
1 9  45  
1 10  
1 

Upvotes: 1

Metris Sovian
Metris Sovian

Reputation: 252

I think you use same $previous_line[$] value for every line, so the the iteration value of $sum will increased constantly. (increased by 1)

You should update $previous_line[$] value on every line:

$previous_line[$y] = $sum;

and you don't need to use this iteration:

for ($z = 0; $z <= $y; $z++) {....}

This is full code:

<?php
$f = 10;
for ($x = 0; $x <= $f; $x++) {
    echo "1"." ";
    $previous_line[$x]=1;
}

echo "<br>";

for ($x = 0; $x < $f; $x++) {
    $sum = 1; 
    echo $sum." ";
    for ($y = 1; $y <= $f-$x-1; $y++) {
        $sum = $sum + $previous_line[$y]; 
        echo $sum." ";              
        $previous_line[$y] =    $sum;                            
}   
echo "<br>";
}

Just try it

Upvotes: 1

Related Questions