Last active
January 25, 2018 17:26
-
-
Save FermiDirak/68d9965c130d8f7f1fb4f82998a02d6f to your computer and use it in GitHub Desktop.
Pascal's Triangle in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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