Skip to content

Instantly share code, notes, and snippets.

@FermiDirak
Last active January 25, 2018 17:26
Show Gist options
  • Save FermiDirak/68d9965c130d8f7f1fb4f82998a02d6f to your computer and use it in GitHub Desktop.
Save FermiDirak/68d9965c130d8f7f1fb4f82998a02d6f to your computer and use it in GitHub Desktop.
Pascal's Triangle in JS
/**
* Generates Pascal's triangle
* @param {number} numRows
* @return {number[][]} Pascal's Priangle
*/
var generate = function(numRows) {
var pascalsTriangle = [];
//initial value at top of triangle
if (numRows >= 1) {
pascalsTriangle.push([1]);
}
//generate numRows rows
for (var i = 1; i < numRows; i++) {
// generate items in each Row
var row = [];
for (var j = 0; j < i + 1; j++) {
var prevRow = pascalsTriangle[i - 1];
var left = prevRow[j - 1] || 0;
var right = prevRow[j] || 0;
row.push(left + right);
}
pascalsTriangle.push(row);
}
return pascalsTriangle;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment