xamples
epeat
ode
pproach
ptimize
est
Write a recursive solution to find the nth number in the Fibonacci sequence
Fibonacci Sequence is 0, 1, 1, 2, 3, 5, 8, 13...
Mathematically Fn = Fn-1 + Fn-2
In words, each number in the sequence is the sum of the previous two integer values. The sequence is started with the numbers 0, 1.
fibonacci(7) // returns 13
Note, we start our Fibonacci Sequence at index 0, thus n=7 is 13. 0, 1, 1, 2, 3, 5, 8, 13...
function fibonacci(num){
if(num > 2) return fibonacci(num - 1) + fibonacci(num - 2);
else if(num <= 1) return num;
else return 1;
}
Because of the two recursive calls our stack grows very quickly and will take a long time for larger Fibonacci numbers...
Use memoization to improve the efficiency of this Fibonacci Sequence
In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
In other words, we shall cache the results of our Fibonacci sequence as we find them. Rather than compute it each time, first we will check if we already have that Fibonacci number in our cache.
var fibonacciTable = [0, 1, 1]
function fibonacci(num){
if(num > 2){
if(!fibonacciTable[num-1]) fibonacciTable[num-1] = fibonacci(num-1);
if(!fibonacciTable[num-2]) fibonacciTable[num-2] = fibonacci(num-2);
return fibonacciTable[num-1] + fibonacciTable[num-2];
}
else if(num <= 1) return num;
else return 1;
}
fibonacci(1000) //returns 4.346655768693743e+208 almost instantly
How can we write a function that can take in any slow running function and give that function the ability to cache?
function memoizer(fun){
var cache = [];
// returns a version of the original function
// that is capable of caching its results
return function(n) {
var idx = n;
if(cache[idx] === undefined) {
cache[idx] = fun(n);
}
return cache[idx]
}
}
Read more here Trasb.org