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?