Skip to content

Instantly share code, notes, and snippets.

@davidcalhoun
Last active December 14, 2017 17:38
Show Gist options
  • Save davidcalhoun/5f2622837eb0ca93e7e6 to your computer and use it in GitHub Desktop.
Save davidcalhoun/5f2622837eb0ca93e7e6 to your computer and use it in GitHub Desktop.
pascal's triangle in javascript
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