Last active
January 26, 2021 21:19
-
-
Save kdubbels/5b6e6ad95f3dc3ac9650567867d9ce74 to your computer and use it in GitHub Desktop.
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
// 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]] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Snippet for a Pascal's Triangle function. Based on a common Scheme/ Lisp implementation.