javascriptfibonaccirosalind

Mortal Fibonacci Rabbits -error at values greater than 6


I try to count Mortal Fibonacci Rabbits. The task assumes that rabbits die out after a fixed number of months.

The picture shows how the number of rabbits changes over time Rabbits

The Fibonacci sequence for Mortal Rabbits looks like this:

{1,1,2,2,3,4,5,7,9,12,16,21,28 (...)}

My code is simple - unfortunately only counts to 6 (inclusive).

function rabbits(n){

if (n<=2){
    return 1
}
else if (n===3 || n===4){
    return 2
}
else {
    f1 = 1
    f2 = 1
    f3 = 2
    f4 = 2
        for (i = 5; i <= n; i++) {
            f = f2 + f3
            f3 = f2
            f2 = f
        }
        return f
    }
}



 console.log(rabbits(1)) // 1
console.log(rabbits(2))  //1 
console.log(rabbits(3))  // 2
console.log(rabbits(4))  //2
console.log(rabbits(5))  //3
console.log(rabbits(6))  //4
console.log(rabbits(7))  //7
console.log(rabbits(8))  //11
console.log(rabbits(9))  //18
console.log(rabbits(10)) //29

From 7 upwards - instead of F (n-2) + F (n-3) - counts F (n-1) + (F (n-2).

I have no idea why this is happening. Where is the error?

I'm just starting an adventure with JS and I'm afraid that complicated code I can not understand (what and why) - so I ask for advice / help modifying the existing one so that the beginner understands.

EDIT//

Okay, problem solved. This is a working code:

var Fib=[]

for(i=1;i<=n;i++){

if(i===1||i===2){

    Fib.push(1)
}

else if(i===3|| i===4){

    Fib.push(2)
}

else{

    fib=Fib[Fib.length-2]+Fib[Fib.length-3]
    Fib.push(fib)
}

}

console.log(Fib)

Solution

  • I'm not sure about the right forumla to get "Fibonacci numbers", I used that one from Wikipedia.

    Anyway I think you could use an array in order to get the previous value, see following please:

    function rabbits(n){
      let fib = [];
      for(let i=1; i<=15; i++){
        fib.push(i+i-1);
      }
      return fib[n-1];
    }
    
    for(let i=1; i<=10; i++){
      console.log("rabbits("+ i + ") = ", rabbits(i));
    }
    <span>From Wikipedia:</span>
    <cite>
    In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones.
    </cite>