Created
February 8, 2017 01:10
-
-
Save pablodenadai/b23162b5b581bda9d3e8fb4fbec0d6de to your computer and use it in GitHub Desktop.
Implementation of Pascal Triangle using Recursive Function - JavaScript ES6
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
| const pascalTriangleRecursive = (n, arr) => { | |
| if (!arr) arr = [[1]] // Create triangle | |
| if (n < 2) return arr // Exit | |
| const prevLine = arr[arr.length - 1] // Get previous line | |
| const newLine = [1] // Create new line | |
| // Populate new line | |
| prevLine.forEach((item, index) => { | |
| if (index === 0) return | |
| if (index === prevLine.length) return | |
| newLine.push(prevLine[index] + prevLine[index - 1]) | |
| }) | |
| newLine.push(1) // Finalise new line | |
| arr.push(newLine) // Insert new line to triangle | |
| return pascalTriangleRecursive(n - 1, arr) // Invoke itself passing the counter and array | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment