Last active
January 11, 2016 15:57
-
-
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/
This file contains 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
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