Created
February 26, 2019 02:06
-
-
Save okovalov/7a95375ac1632e6866f4d02d7c5b166d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Fibonacci | |
* | |
* 1, 1, 2, 3, 5, 8, 13, 21, 34 | |
* | |
* fibonacci = O(n^2) - exponential | |
* fibMemo = O(n) - linear | |
*/ | |
/** O(n^2) **/ | |
const fibonacci = position => { | |
if (position < 3) { | |
return 1 | |
} | |
return fibonacci(position - 1) + fibonacci(position - 2) | |
} | |
/** O(n) **/ | |
const fibMemo = (position, cache = []) => { | |
if (cache[position]) return cache[position] | |
if (position < 3) return 1 | |
cache[position] = fibMemo(position - 1, cache) + fibMemo(position - 2, cache) | |
return cache[position] | |
} | |
console.time('Time for all'); | |
for (let i = 0; i <= 500 ; i++ ) { | |
console.time(`Time for ${i}`); | |
console.log(`Fibo(${i}) = ${fibMemo(i, [])}`) | |
console.timeEnd(`Time for ${i}`) | |
} | |
console.timeEnd('Time for all') // Time for all: 168.497ms | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment