Skip to content

Instantly share code, notes, and snippets.

@godrm
Created July 11, 2017 00:00
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 godrm/e0e6d6d5a280728287a10f1a830fcf4d to your computer and use it in GitHub Desktop.
Save godrm/e0e6d6d5a280728287a10f1a830fcf4d to your computer and use it in GitHub Desktop.
Functional Pascal Triangle
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