I need some help with a program I\'m writing for my Programming II class at universtiy. The question asks that one calculates the Fibonacci sequence using recursion. One mus
This is a very quick one using memoisation. First I initialise my cache dictionary.
var cache = [Int:Int]()
Then I create my Fibonacci number generator. Since it is a recursive function, every call to the function would theoretically compute the whole Fibonacci sequence again up to the requested number. This is why we use the cache, to speed up the recursive function:
func fibonacci(_ number: Int) -> Int {
// if the value is in the dictionary I just return it
if let value = cache[number] { return value }
// Otherwise I calculate it recursively.
// Every recursion will check the cache again,
// this is why memoisation is faster!
let newValue = number < 2 ? number : fibonacci(number - 1) + fibonacci(number - 2)
cache[number] = newValue
return newValue
}
I can save my sequence in an array like this:
var numbers = Array(0..<10).map(fibonacci) //[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Or use the function in a loop.