Skip to content

Instantly share code, notes, and snippets.

@hlung
Last active January 11, 2016 15:57
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 hlung/4009276a45b3a04e2455 to your computer and use it in GitHub Desktop.
Save hlung/4009276a45b3a04e2455 to your computer and use it in GitHub Desktop.
A Swift 2 function that calculates a fibonacci number, then cached it in a dictionary for later use. Max value of `Double` is 1.79769313486232e+308. Note: there is a faster way to calculate this if you need to jump later numbers. It's called "fast doubling", see https://vinayakgarg.wordpress.com/2012/11/07/fastest-way-to-compute-fibonacci-number/
typealias NumType = Double
var calculatedFibs = [NumType: NumType]()
func fib(num: NumType) -> NumType {
guard num > 1 else { // when num is 0, 1, just return 0, 1.
return num
}
if let cached = calculatedFibs[num] { // read cache
return cached
}
// calculate recursively
let result = fib(num - 1) + fib(num - 2)
// write cache
calculatedFibs[num] = result
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment