Last active
October 9, 2015 21:27
-
-
Save proxpero/5de697c79ff81c85ddc7 to your computer and use it in GitHub Desktop.
SICP exercise 1.12 in Swift
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
//: SICP Exercise 1.12 | |
//: //: Xcode 7.0, Swift 2.0 | |
/* The following pattern of numbers is called Pascal’s triangle. | |
1 | |
1 1 | |
1 2 1 | |
1 3 3 1 | |
1 4 6 4 1 | |
. . . | |
The numbers at the edge of the triangle are all 1, and each number inside the triangle is the sum of the two numbers above it.(1) Write a procedure that computes elements of Pascal’s triangle by means of a recursive process. | |
(1) The elements of Pascal’s triangle are called the binomial coefficients, because the nth row consists of the coefficients of the terms in the expansion of (x+y)^n. | |
I take this assignment to be asking for a function that takes a row number and returns the elements for that row. | |
*/ | |
func elementsAtRow(row: Int) -> [Int] { | |
var elements = [Int]() | |
func element(row: Int, _ index: Int) -> Int { | |
guard index != 0 else { return 1 } | |
guard row != index else { return 1 } | |
return element(row - 1, index - 1) + element(row - 1, index) | |
} | |
for i in (0...row) { | |
elements.append(element(row, i)) | |
} | |
return elements | |
} | |
assert(elementsAtRow(0) == [1]) | |
assert(elementsAtRow(1) == [1,1]) | |
assert(elementsAtRow(2) == [1,2,1]) | |
assert(elementsAtRow(3) == [1,3,3,1]) | |
assert(elementsAtRow(4) == [1,4,6,4,1]) | |
assert(elementsAtRow(5) == [1,5,10,10,5,1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment