Skip to content

Instantly share code, notes, and snippets.

@proxpero
Last active October 9, 2015 21:27
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 proxpero/9524a551aaccdf4fa693 to your computer and use it in GitHub Desktop.
Save proxpero/9524a551aaccdf4fa693 to your computer and use it in GitHub Desktop.
SICP exercise 1.11 in Swift
//: SICP Exercise 1.11
//: Xcode 7.0, Swift 2.0
//: A function f is defined by the rule that f(n)=n if n<3 and f(n)=f(n−1)+2f(n−2)+3f(n−3) if n≥3. Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process.
func recursive(n: Int) -> Int {
if n < 3 { return n }
else { return recursive(n-1) + 2 * recursive(n-2) + 3 * recursive(n-3) }
}
for n in (0...10) {
print("f(\(n)) = \(recursive(n))")
}
// f(0) = 0
// f(1) = 1
// f(2) = 2
// f(3) = 4
// f(4) = 11
// f(5) = 25
// f(6) = 59
// f(7) = 142
// f(8) = 335
// f(9) = 796
// f(10) = 1892
func iterative(n: Int) -> Int {
if n < 3 { return n }
// This iteration's `a` value will be the next iteration's `b` value,
// this iterations's `b` will be the next iteration's `c`, and so on
// until at last it exits `while` and returns f(n+1)'s `a` value, which equals f(n).
func iter(a: Int, _ b: Int, _ c: Int, counter: Int) -> Int {
while counter <= n {
return iter(fn(a, b, c), a, b, counter: counter+1)
}
return a
}
func fn(a: Int, _ b: Int, _ c: Int) -> Int {
return (1 * a) + (2 * b) + (3 * c)
}
// 2 = f(n-1), 1 = f(n-2), 0 = f(n-3), when n = 3
return iter(2, 1, 0, counter: 3)
}
for n in (0...10) {
print("f(\(n)) = \(iterative(n))")
}
// f(0) = 0
// f(1) = 1
// f(2) = 2
// f(3) = 4
// f(4) = 11
// f(5) = 25
// f(6) = 59
// f(7) = 142
// f(8) = 335
// f(9) = 796
// f(10) = 1892
/*
Iterative version in Scheme...
(define (iteritive n)
(define (iter a b c counter)
(if (> counter n)
a
(iter (fn a b c) a b (+ counter 1))
)
)
(define (fn a b c)
(+ a (* 2 b) (* 3 c))
)
(if (< n 3)
n
(iter 2 1 0 3)
)
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment