Created
November 2, 2020 20:41
-
-
Save apacheli/ef94407d97ffcb6458580149fb0a39e3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 centerString(string, distance) { | |
| const spaces = ' '.repeat(distance) | |
| return spaces + string + spaces | |
| } | |
| function calculateTriangle(n, a = [[1]]) { | |
| if (n < 2) { | |
| return a | |
| } | |
| const previousRow = a[a.length - 1] | |
| const currentRow = [1] | |
| for (let i = 1; i < previousRow.length; i++) { | |
| currentRow[i] = previousRow[i] + previousRow[i - 1] | |
| } | |
| currentRow.push(1) | |
| a.push(currentRow) | |
| return calculateTriangle(n - 1, a) | |
| } | |
| function buildPascalTriangle(n) { | |
| const triangle = calculateTriangle(n) | |
| let str = '' | |
| let last = triangle[triangle.length - 1].join(' ') | |
| for (let i = 0; i < triangle.length - 1; i++) { | |
| const numbers = triangle[i].join(' ') | |
| str += centerString(numbers, (last.length - numbers.length) / 2) + '\n' | |
| } | |
| str += last | |
| return str | |
| } | |
| const d = buildPascalTriangle(10) | |
| console.log(d) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment