Skip to content

Instantly share code, notes, and snippets.

@kdubbels
Last active January 26, 2021 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kdubbels/5b6e6ad95f3dc3ac9650567867d9ce74 to your computer and use it in GitHub Desktop.
Save kdubbels/5b6e6ad95f3dc3ac9650567867d9ce74 to your computer and use it in GitHub Desktop.
Pascal's Triangle
// Generates Pascal's triangle of any number of rows
//
// https://en.wikipedia.org/wiki/Pascal%27s_triangle
function nextRow(row) {
const right = row.concat(0)
const left = [0].concat(row)
return left.map((x, i) => x + right[i]);
}
function triangle(row, rows) {
if (rows === 0) {
return [];
} else {
return [row, triangle(nextRow(row), rows-1)]
}
}
function printPascal(arr){
return arr.reduce((acc, item, index) => {
return index === 0 ? acc.concat([item]) : acc.concat(printPascal(item))
}, [])
}
printPascal(triangle([1], 5)) // [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
@kdubbels
Copy link
Author

Snippet for a Pascal's Triangle function. Based on a common Scheme/ Lisp implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment