Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.