Last active
December 14, 2017 17:38
-
-
Save davidcalhoun/5f2622837eb0ca93e7e6 to your computer and use it in GitHub Desktop.
pascal's triangle in javascript
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 pt(lineLimit, lines) { | |
// Seed the first value. | |
if(!lines || lines.length === 0) return pt(lineLimit, [[1]]); | |
var newLine = []; | |
var lastLine = lines[lines.length - 1]; | |
// Fill out inner values | |
for(var i=1, len=lastLine.length; i<len; i++) { | |
newLine.push(lastLine[i - 1] + lastLine[i]); | |
} | |
// Add 1s border to both sides. | |
newLine.unshift(1); | |
newLine.push(1); | |
// Add the new line to the lines array. | |
lines.push(newLine); | |
if(lineLimit === lines.length) { | |
// Finished! | |
return lines; | |
} else { | |
// Generate the next line. | |
return pt(lineLimit, lines); | |
} | |
} | |
pt(5); | |
/* | |
Output: | |
[ | |
[ 1 ], | |
[ 1, 1 ], | |
[ 1, 2, 1 ], | |
[ 1, 3, 3, 1 ], | |
[ 1, 4, 6, 4, 1 ] | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment