Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I recursively generate an Array of the Fibonacci sequence?

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;
};
like image 801
TheRealFakeNews Avatar asked Apr 05 '16 00:04

TheRealFakeNews


2 Answers

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.

like image 98
SlySherZ Avatar answered Nov 15 '22 21:11

SlySherZ


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))
like image 42
Damian Pavlica Avatar answered Nov 15 '22 21:11

Damian Pavlica