Created
July 11, 2017 00:00
-
-
Save godrm/e0e6d6d5a280728287a10f1a830fcf4d to your computer and use it in GitHub Desktop.
Functional Pascal 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
func makePascalTriangle(numOfRows: Int) -> ([[Int]]) { | |
func getNextRow(_ arr: [Int]) -> [Int] { | |
let a = zip([0]+arr, arr+[0]) | |
return a.map({ | |
(e: (Int, Int)) -> Int in | |
e.0 + e.1 | |
}) | |
} | |
func helper(_ countDown: Int, results: [[Int]]) -> (Int, [[Int]]) { | |
if countDown == 0 { | |
return (countDown, results) | |
} | |
let row = getNextRow(results.last!) | |
return helper(countDown - 1, results: results + [row]) | |
} | |
let initialPascal = [1] | |
let (_, pascals) = helper(numOfRows, results: [initialPascal]) | |
return pascals | |
} | |
makePascalTriangle(numOfRows: 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment