Skip to content

Instantly share code, notes, and snippets.

@chefnobody
Created March 18, 2018 17:49
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 chefnobody/26ca7f8fc721833d28dc50b4ccac1fd9 to your computer and use it in GitHub Desktop.
Save chefnobody/26ca7f8fc721833d28dc50b4ccac1fd9 to your computer and use it in GitHub Desktop.
Slow and Fast Fibonacci
//: Playground - noun: a place where people can play
import Foundation
import UIKit
func fib(_ n: Int) -> Int {
if n == 0 { return 0 }
if n == 1 { return 1 }
return fib(n - 1) + fib(n - 2)
}
// Cache the previously computed fib(n) value
func fibMemoed(_ n: Int, memo: inout [Int: Int]) -> Int {
if n == 0 { return 0 }
if n == 1 { return 1 }
if memo[n] == nil {
memo[n] = fibMemoed(n - 1, memo: &memo) + fibMemoed(n - 2, memo: &memo)
}
return memo[n]!
}
// Measuers, roughly the time it took for a block of "work" to complete
func measure(work: () -> Void) -> CFTimeInterval {
let startTime = CACurrentMediaTime()
work()
let endTime = CACurrentMediaTime()
return endTime - startTime
}
// -------------
let n = 21
// Sould be fast
measure {
var memo = [Int: Int]()
let _ = fibMemoed(n, memo: &memo)
}
// Should be slow(er)
measure {
let _ = fib(n)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment