Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function fib(n) {
- if(n <= 2) {
- return 1;
- } else {
- return fib(n-1) + fib(n-2);
- }
- }
- function fibMemo(n, memo) {
- if(memo[n]) { return memo[n]; }
- if(n <= 2) {
- return 1;
- } else {
- memo[n] = fibMemo(n-1, memo) + fibMemo(n-2, memo);
- }
- return memo[n];
- }
- function fibBottomUp(n, memo) {
- let f;
- for(let k = 1; k <= n+1; k++) {
- if(k <= 2) {
- f = 1;
- } else {
- f = memo[k - 1] + memo[k - 2];
- }
- memo[k] = f
- }
- return memo[n];
- }
- function time(f, ...a) {
- return new Promise(
- (ok, nok) => {
- ok(f(...a));
- }
- );
- }
- (async () => {
- let start = new Date().getTime();
- console.log('Computing value with Fibo Recursive Naive ...');
- console.log(await time(fib, 44));
- console.log('OK in ' + (new Date().getTime() - start)/1000 + 's');
- start = new Date().getTime();
- console.log('Computing value with Fibo DP Memoizing ...');
- console.log(await time(fibMemo, 44, []));
- console.log('OK in ' + (new Date().getTime() - start)/1000 + 's');
- start = new Date().getTime();
- console.log('Computing value With Fibo DP Bottom Up ...');
- console.log(await time(fibBottomUp, 44, []));
- console.log('OK in ' + (new Date().getTime() - start)/1000 + 's');
- })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement