Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. function fib(n) {
  2.  
  3. if(n <= 2) {
  4. return 1;
  5. } else {
  6. return fib(n-1) + fib(n-2);
  7. }
  8. }
  9.  
  10. function fibMemo(n, memo) {
  11.  
  12. if(memo[n]) { return memo[n]; }
  13.  
  14. if(n <= 2) {
  15. return 1;
  16. } else {
  17. memo[n] = fibMemo(n-1, memo) + fibMemo(n-2, memo);
  18. }
  19. return memo[n];
  20. }
  21.  
  22. function fibBottomUp(n, memo) {
  23. let f;
  24. for(let k = 1; k <= n+1; k++) {
  25. if(k <= 2) {
  26. f = 1;
  27. } else {
  28. f = memo[k - 1] + memo[k - 2];
  29. }
  30. memo[k] = f
  31. }
  32. return memo[n];
  33. }
  34.  
  35. function time(f, ...a) {
  36.  
  37. return new Promise(
  38. (ok, nok) => {
  39. ok(f(...a));
  40. }
  41. );
  42.  
  43. }
  44.  
  45. (async () => {
  46. let start = new Date().getTime();
  47. console.log('Computing value with Fibo Recursive Naive ...');
  48. console.log(await time(fib, 44));
  49. console.log('OK in ' + (new Date().getTime() - start)/1000 + 's');
  50.  
  51. start = new Date().getTime();
  52. console.log('Computing value with Fibo DP Memoizing ...');
  53. console.log(await time(fibMemo, 44, []));
  54. console.log('OK in ' + (new Date().getTime() - start)/1000 + 's');
  55.  
  56. start = new Date().getTime();
  57. console.log('Computing value With Fibo DP Bottom Up ...');
  58. console.log(await time(fibBottomUp, 44, []));
  59. console.log('OK in ' + (new Date().getTime() - start)/1000 + 's');
  60. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement