Created
June 20, 2014 08:59
-
-
Save shaundon/d84953a47f995a79eb0d to your computer and use it in GitHub Desktop.
Creates a 2D array that contains a pascal's triangle.
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
function pascal(rows) { | |
var pascalsTriangle = []; | |
for (var row=1; row<=rows; row++) { | |
var rowResults = []; | |
if (pascalsTriangle[row-2]) { | |
var aboveRow = pascalsTriangle[row-2]; | |
for (var i=0; i<row; i++) { | |
if (aboveRow[i-1] && aboveRow[i]) { | |
rowResults.push(aboveRow[i-1] + aboveRow[i]); | |
} | |
else { | |
rowResults.push(1); | |
} | |
} | |
} | |
else { | |
rowResults.push(1); | |
} | |
pascalsTriangle.push(rowResults); | |
} | |
console.log(pascalsTriangle); | |
return pascalsTriangle; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment