skip to Main Content
function tribonacci(arr, n){
    let sum = 0;
    for(let i= arr.length-1; i > arr.length-4; i--){
       sum += arr[i]     
    }

    while(arr.length < n){
      arr.push(sum);
    }
  
    return arr; 
}

console.log(tribonacci([1, 1, 1], 10));

With ([1, 1, 1], 10) it should log [1, 1, 1, 3, 5, 9, 17, 31, 57, 105] since it’s following a tribonacci sequence and we want it to stop executing once we have 10 integers.

Initially the for loop executed fine, so if I gave it [1,1,1] it would log [1,1,1,3] and if I gave it [1,1,1,3] it would print [1,1,1,3,5] and so on. Then I added the while loop to specify the length(n) at which I wanted the array to end. Now the output keeps logging 3 over and over until there’s 10 integers: [1, 1, 1, 3, 3, 3, 3, 3, 3, 3].

I understood that it’s repeatedly pushing the next number in the sequence (which is 3), having calculated [1,1,1] instead of recalculating starting from the last index in the array… So I tried a bunch of different things like nesting the for loop inside the while loop or attempting a do…while loop etc to no avail. Do I need to keep resetting the calculation in the while loop? What am I doing wrong and how do I fix this?

2

Answers


  1. Your code executes each loop only once, so you calculate the sum of the three first elements in the array once and then proceed to append this sum to the array until its lenght reaches n.

    Instead you want to calculate the sum n – 3 times by putting your loops together:

    function tribonacci(arr, n){
        // It's a good idea to add validation for the array's length to avoid errors 
        if(arr.length < 3){
            return arr;
        }
        while(arr.length < n){
            let sum = 0;
            for(let i= arr.length-1; i > arr.length-4; i--){
                sum += arr[i]     
            }
            arr.push(sum);
        }
      
        return arr; 
    }
    
    console.log(tribonacci([1, 1, 1], 10));
    
    Login or Signup to reply.
  2. You need to repeatedly calculate the sum of the last 3 numbers in the array and add that sum to the array until the array length is n.

    const tribonacci = (arr, n) => {
        // TODO: Validate arguments (like ensure arr is at least [1,1,1])
        
        while (arr.length < n) {
            arr.push(arr[arr.length - 3] + arr[arr.length - 2] + arr[arr.length - 1]);
        }
        return arr;
    };
    
    console.log(tribonacci([1,1,1], 20));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search