Advertisement
Guest User

Pascal Triangle

a guest
Jul 20th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.80 KB | None | 0 0
  1. function pascals_triangle($n) {
  2.   // Your code here
  3.   $firstRow = [1];
  4.   $secondRow = [1,1];
  5.   $rows = [
  6.     1 => $firstRow,
  7.     2 => $secondRow
  8.   ];
  9.  
  10.   // when n is 1 or 2, return rowOne or rowTwo
  11.   if ($n == 1) {
  12.     return $rows[1];
  13.   }
  14.   if ($n == 2) {
  15.     return array_merge($firstRow, $secondRow);
  16.   }
  17.  
  18.   for ($row = 3; $row <= $n; $row++) {
  19.     $prev = $rows[$row-1];
  20.    
  21.     // start is always 1
  22.     $currentRow = [1];
  23.    
  24.     for ($i = 1; $i < $row - 1; $i++) {
  25.       // current num
  26.       $currentNum = $prev[$i - 1] + $prev[$i];
  27.       $currentRow[] = $currentNum;
  28.     }
  29.    
  30.     // add the end
  31.     $currentRow[] = 1;
  32.     $rows[] = $currentRow;
  33.   }
  34.  
  35.   $result = [];
  36.   foreach ($rows as $row) {
  37.     $result = array_merge($result, $row);
  38.   }
  39.  
  40.   return $result;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement