I've seen several posts on generating a given fibonacci sequence, such as this one. However, I can't figure out how to generate the sequence (return an array) of fibonnaci numbers for a given n
using recursion. What I have clearly doesn't work, but I really can't figure out how to do it otherwise.
var fibArray = function(n) {
var f = [];
n < 2 ? f.push(n) : f.push(fibArray(n-1) + fibArray(n-2));
return f;
};
Notice that you start each function call with an empty array and then only add 1 member to it. That won't work.
You have to add the new element to the array that was returned from the previous fib(n - 1)
step. Like so:
function fib (n) {
if (n < 2) {
return [1];
}
if (n < 3) {
return [1, 1];
}
var a = fib(n - 1);
a.push(a[n - 2] + a[n - 3]);
return a;
};
The nth
number appears on the position n - 1
on the array. That justifies the n - 2 = n - 1 - 1
and n - 3 = n - 2 - 1
.
A slightly modified version from the previous answer:
function fib(n) {
if (n == 0) return [0]
if (n == 1) return [0, 1]
const arr = fib(n - 1)
return [...arr, arr[n-1] + arr[n-2]]
}
console.log(fib(15))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With