...

/

Solution Review: Pascal's Triangle

Solution Review: Pascal's Triangle

Solution review to the exercise for recursion and function composition.

Solution

The problem can be solved using either the function composition or recursion. Let’s look at the two approaches individually.

Recursion approach

For this solution, factor out the base cases and recursion cases.

Press + to interact
function getPascalsLine(x) {
if (x === 0) {
// Basecase # 1
// top element of pyramid has only one value
// the value [1]
return [1];
}
else {
// recursive case
// It will have atleast two 1's
var line = [1]; // start by adding first 1 in initialisation
var previousLine = getPascalsLine(x - 1); // get previous line
// Traverse previous line two values at a time
// Ignore the last value as we need some of adjacent pairs
// so loop runs for i less than previousLine.length - 1
for (let i = 0; i < previousLine.length - 1; i++) {
// add sum of i and i+1 index and push to line array
line.push(previousLine[i] + previousLine[i + 1]);
}
// finally push the ending [1]
line.push(1);
// return the final line
return line;
}
}
console.log("5th line is: ",getPascalsLine(5));

The two cases can be outlined like this.

  • Base case (lines 2 to 7): For zeroth line, the array will only have a single value of 1, so we can conclusively return [1].
  • Recursive case (lines 8 to 24): For any other line, we have a value of 1 at
...