Created
September 4, 2024 19:10
-
-
Save jjhiggz/b0b6a4494fb5921f5054ac593854c9e9 to your computer and use it in GitHub Desktop.
different Fibonacci answers
This file contains 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
const at = <T,>(arr: T[], index: number) => index < 0 | |
? arr[arr.length + index] | |
: arr[index]; | |
let recursiveFibCount = 0 | |
const rFibonnaci = (num = 1, prevSeq: number[] = [0]): number => { | |
if(prevSeq.length === num) { | |
return at(prevSeq, -1) | |
} | |
if(prevSeq.length === 1) return rFibonnaci(num, [0, 1]) | |
recursiveFibCount += 1 | |
return rFibonnaci(num, [...prevSeq, at(prevSeq, -2) + at(prevSeq, -1)]) | |
} | |
let whileLoopFibCount = 0 | |
const wFibonnaci = (num = 1): number => { | |
const prevSeq = [0] | |
while(prevSeq.length < num){ | |
whileLoopFibCount += 1 | |
switch(prevSeq.length){ | |
case 1: | |
prevSeq.push(1) | |
default: | |
prevSeq.push(at(prevSeq, -2) + at(prevSeq, -1)) | |
} | |
} | |
return at(prevSeq, -1) | |
} | |
const fib = [0] | |
let memoizedFibCount = 0 | |
const wFibonnaciMemoized = (num = 1): number => { | |
while(fib.length < num){ | |
memoizedFibCount++ | |
switch(fib.length){ | |
case 1: | |
fib.push(1) | |
default: | |
fib.push(at(fib, -2) + at(fib, -1)) | |
} | |
} | |
// console.log(fib) | |
return at(fib, num - 1) | |
} | |
const range = (n: number) => { | |
const arr = [] | |
for(let i = 1; i <= n; i++){ | |
arr.push(i) | |
} | |
return arr | |
} | |
const nums = range(50) | |
nums.map(n => rFibonnaci(n)) | |
nums.map(n => wFibonnaci(n)) | |
nums.map(n => wFibonnaciMemoized(n)) | |
console.log({ | |
whileLoopFibCount, | |
recursiveFibCount, | |
memoizedFibCount, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment