Skip to content

Instantly share code, notes, and snippets.

@messerc
Created October 19, 2017 16:40
Show Gist options
  • Save messerc/e4d7ab34e751107abe4c7e8d9dc96159 to your computer and use it in GitHub Desktop.
Save messerc/e4d7ab34e751107abe4c7e8d9dc96159 to your computer and use it in GitHub Desktop.
// if numRows is > 2: initialize an array that will hold our pascals triangle with [[1], [1, 1]]
// generate a loop based on the numRows input and start at i = 2 and initialize a new row
// inside each iteration, produce an inner loop of j that will help produce the current row
// reach into our pascals triangle array, sum up the appropriate values, and push to our row
// finish by pushing a final 1 to the current row and then pushing that row to our pascals triangle array
// return our pascals array
var generate = function(numRows) {
if (numRows === 0) {
return [];
}
if (numRows === 1) {
return [[1]];
}
let pascals = [[1], [1, 1]];
for (let i = 2; i < numRows; i++) {
let row = [];
row.push(1);
for (let j=0; j < pascals[i-2].length; j++) {
row.push(pascals[i-1][j] + pascals[i-1][j+1]);
}
row.push(1);
pascals.push(row);
}
return pascals
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment