Created
June 8, 2021 20:35
-
-
Save jeromecovington/c04eeabba88f6575412a5369ada72638 to your computer and use it in GitHub Desktop.
Dynamic programming fibonacci example
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
// Naive recursion. | |
function fib1(n) { | |
if (n <= 1) { | |
return n | |
} | |
return fib1(n - 1) + fib1(n - 2) | |
} | |
{ | |
console.log('fib1') | |
const start = Date.now() | |
console.log(fib1(100)) | |
const end = Date.now() | |
console.log(end - start) | |
console.log('===') | |
} | |
// Dynamic "top-down" w/momoization. | |
const fibs = [0, 1] | |
function fib2(n) { | |
if (fibs[n] === undefined) { | |
fibs[n] = fib2(n - 1) + fib2(n - 2) | |
} | |
return fibs[n] | |
} | |
{ | |
console.log('fib2') | |
const start = Date.now() | |
console.log(fib2(100)) | |
const end = Date.now() | |
console.log(end - start) | |
console.log('===') | |
} | |
// Dynamic "bottom-up". | |
function fib3(n) { | |
if (n === 0) { | |
return n | |
} | |
let previous = 0 | |
let current = 1 | |
for (let i = 0; i < n - 1; i++) { | |
let newValue = previous + current | |
previous = current | |
current = newValue | |
} | |
return current | |
} | |
{ | |
console.log('fib3') | |
const start = Date.now() | |
console.log(fib3(100)) | |
const end = Date.now() | |
console.log(end - start) | |
console.log('===') | |
} | |
/* | |
fib1 | |
? | |
? | |
=== | |
fib2 | |
354224848179262000000 | |
1 | |
=== | |
fib3 | |
354224848179262000000 | |
0 | |
=== | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment