Created
September 29, 2019 15:07
-
-
Save codeOfRobin/0f9103227792727f6b0cad5383ba19a2 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
func fibonacci(_ number: Int, memoizingDict: inout [Int: Int]) -> Int { | |
switch number { | |
case 0: | |
return 0 | |
case 1: | |
return 1 | |
default: | |
let numberMinus1: Int | |
let numberMinus2: Int | |
if memoizingDict[number - 1] == nil { | |
/// to perf test vs a non-memoized version | |
// var dict: [Int: Int] = [:] | |
// let x = fibonacci(number - 1, memoizingDict: &dict) | |
let x = fibonacci(number - 1, memoizingDict: &memoizingDict) | |
memoizingDict[number - 1] = x | |
numberMinus1 = x | |
} else { | |
numberMinus1 = memoizingDict[number - 1]! | |
} | |
if memoizingDict[number - 2] == nil { | |
/// to perf test vs a non-memoized version | |
// var dict: [Int: Int] = [:] | |
// let x = fibonacci(number - 2, memoizingDict: &dict) | |
let x = fibonacci(number - 2, memoizingDict: &memoizingDict) | |
memoizingDict[number - 2] = x | |
numberMinus2 = x | |
} else { | |
numberMinus2 = memoizingDict[number - 2]! | |
} | |
return numberMinus1 + numberMinus2 | |
} | |
} | |
func fibonacci(_ number: Int) -> Int { | |
var dict: [Int: Int] = [:] | |
return fibonacci(number, memoizingDict: &dict) | |
} | |
print(fibonacci(40)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
memoized version: finishes in 0.21s
vs non memoized
That's a 1000x difference!