Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * @Construct a Triangle of Pascal
- * @since 2011-09-16
- * @author Edson Chimello
- * @site: http://www.w3tools.info/2011/10/pascal-php-class.html
- *
- * FREE TO USE
- */
- class Pascal
- {
- /**
- *
- * @param $lin
- * @return triangle
- */
- public function getTriangle($lin)
- {
- $cols = $lin * 2 - 1;
- if ($cols < 0)
- {
- $cols = 0;
- }
- for ($i = 0; $i < $lin; $i++)
- {
- for ($j = 0; $j < $cols; $j++)
- {
- $pascal[$i][$j] = 0;
- $pascal[0][$lin - 1] = 1;
- $cont = 0;
- for ($i = 1; $i < $lin; $i++)
- {
- for ($j = $lin - 1 - $i; $j < $cols; $j += 2)
- {
- if ($cont <= $i)
- {
- if ($j == 0 || $j == $cols - 1)
- {
- $pascal[$i][$j] = 1;
- }else{
- $pascal[$i][$j] = $pascal[$i - 1][$j - 1] +
- $pascal[$i - 1][$j + 1];
- }
- }
- $cont++;
- }
- $cont = 0;
- }
- }
- }
- for ($i = 0; $i < $lin; $i++)
- {
- for ($j = 0; $j < $cols; $j++)
- {
- if ($pascal[$i][$j] != 0)
- echo sprintf("%4s",$pascal[$i][$j]) . ' ';
- }
- echo "<br />";
- }
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement