Getting a values from nodes

65 Views Asked by At

The goal: get horizontal values of vertical level N where level 1 is pinacle node (1).

enter image description here

Example: level 4 as input should produce: | 1 | 3 | 3 | 1 |

Note: the sum of two adjacent nodes of level N is the value of node of level N + 1 in between those nodes of level N (marked with circles on the image).

I have accomplished this task with the help of loops and arrays:

function getValues($level) {
  $level = $level === 0 ? 1 : abs((int) $level);
  $data  = array(1 => array(1 => 1)
, 2 => array(1 => 1, 2 => 1));
  for ($i = 3; $i <= $level; $i++) {
for ($ii = 1; $ii <= $i; $ii++) {
  $val = $ii === 1 || $ii === $i  
 ? 1 : $data[$i - 1][$ii - 1] + $data[$i - 1][$ii];
  $data[$i][$ii] = $val;
}
  }
  return $data[$level];
}
echo '| '.implode(' | ', getValues(7))." |\n";

It works pretty good, but...

Question: how can I do the same with the help of Math instead of using control structures of programming language? Probably I need logarithms?

1

There are 1 best solutions below

0
On BEST ANSWER

You're trying to get the $N$th row of Pascal's triangle.

The $N$th row can be calculated with the formulae:

$$ \mathbf{C}_k^n= {n \choose k} = \frac{n!}{k!(n-k)!} $$ where, $n$ is the row and $k$ is the vertical position.