Last active
March 28, 2018 13:51
-
-
Save cristhianleonli/84118ff30591c93fbede2b30473af608 to your computer and use it in GitHub Desktop.
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
// recursively with redundant calculations | |
func fibo(n: Int) -> Int { | |
if n < 2 { return n } | |
return fibo(n: n - 1) + fibo(n: n - 2) | |
} | |
// with memoization | |
var memo = Dictionary<Int, Int>() | |
func fibMemo(_ n: Int) -> Int { | |
if let result = memo[n] { return result } | |
if n < 2 { return n } | |
let result = fibMemo(n - 1) + fibMemo(n - 2) | |
memo[n] = result | |
return result | |
} | |
let results = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] | |
for i in 0...11 { | |
assert(fibMemo(i) == results[i]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment