سؤال

I am trying to get pascal's triangle using two dimensional array. But it not works. can anyone solve this program. Thanks in advance.

    <html>
<body>
<div>
    <form name="form1" action="pascaltriangle4.php" method="post">
        Enter the number of rows in pyramid of stars you wish to see  : <input type="text" name="n">
                <input type="submit" name="submit" value="submit">
    </form>
    </div>
    <div>
    <table>
<?php
if($_POST['submit']==='submit')
{
    ini_set('display_errors', 1);
    error_reporting(E_ALL);

    $n=$_POST['n'];
    $arr=array();
    //print_r($arr);
    for($i=0;$i<=$n;$i++)
    {
        echo "<tr>";
        for($j=0;$j<=$i;$j++)
        {
            if($j==0)
            {
                //echo "1";
                $arr[$i][$j]=1;
                //print_r($arr);
                if($n!=$i)
                {
                    echo "<td colspan='".($n-$i)."'></td>";
                }
                    echo "<td>".$arr[$i][$j]."</td>";
                    echo "<td></td>";
                }
            elseif($i==$j)
            {
                //echo "1";
                $arr[$i][$j]=1;
                //echo $arr;
                echo "<td>".$arr[$i][$j]."</td>";
                    //echo "<td></td>";
            }
            else
            {
                $arr[$i][$j]=$arr[$i-1][$j-1]+$arr[$i-1][$j];
                echo "<td>".$arr[$i][$j]."</td>";
                echo "<td></td>";
            }

        }echo "</tr>";
    }
    //echo "<pre>";
    //print_r($arr);
    //echo "</pre>";
}
?>
</table></div>
<body>
</body>
</html>
هل كانت مفيدة؟

المحلول

$size = 32;
$pascal = array(
    array(1),
);

for ($i = 1; $i <= $size; ++$i) {
    $prevCount = count($pascal[$i-1]);
    for ($j = 0; $j <= $prevCount; ++$j) {
        $pascal[$i][$j] = (
            (isset($pascal[$i-1][$j-1]) ? $pascal[$i-1][$j-1] : 0) + 
            (isset($pascal[$i-1][$j]) ? $pascal[$i-1][$j] : 0)
        );
    }
}
var_dump($pascal);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top