Skip to content

Instantly share code, notes, and snippets.

@tomanistor
Last active May 11, 2024 10:04
Show Gist options
  • Save tomanistor/4b3d22e241f004aed32229dc70678af1 to your computer and use it in GitHub Desktop.
Save tomanistor/4b3d22e241f004aed32229dc70678af1 to your computer and use it in GitHub Desktop.
Tribonacci Sequence

Well met with Fibonacci bigger brother, AKA Tribonacci.

As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. And, worse part of it, regrettably I won't get to hear non-native Italian speakers trying to pronounce it :(

So, if we are to start our Tribonacci sequence with [1,1,1] as a starting input (AKA signature), we have this sequence:

[1,1,1,3,5,9,17,31,...]

But what if we started with [0,0,1] as a signature? As starting with [0,1] instead of [1,1] basically shifts the common Fibonacci sequence by once place, you may be tempted to think that we would get the same sequence shifted by 2 places, but that is not the case and we would get:

[0,0,1,1,2,4,7,13,24,...]

Well, you may have guessed it by now, but to be clear: you need to create a fibonacci function that given a signature array/list, returns the first n elements - signature included of the so seeded sequence.

Signature will always contain 3 numbers; n will always be a non-negative number; if n==0, then return an empty array and be ready for anything else which is not clearly specified ;)

function tribonacci(signature,n) {
var trib = signature;
for (i = 3; i < n; i++) {
trib.push((trib[i-1] + trib[i-2] + trib[i-3]));
}
return trib.slice(0, n);
}
@web-dev-london
Copy link

function tribonacci(signature, n) {
for(let i = 0; i < n -3; i++) {
signature.push(signature.slice(i) .reduce(( a , b) => a + b),);
}
return signature.slice(0, n);
}

@DvoeglazovIlya
Copy link

Loop faster than recursion and need lower resurce.

function tribonacci(signature, n) {
  let [a, b, c] = signature;

  let result = [];

  for (let i = 2; i <= n; i++) {
    let d = a + b + c;
    a = b;
    b = c;
    c = d;
    result.push(c);
  }

  return result;
}

console.log(tribonacci([1, 1, 1], 7)); // [ 3, 5, 9, 17, 31, 57 ]
console.log(tribonacci([1, 1, 1], 0)); // []
console.log(tribonacci([0, 0, 1], 7)); // [ 1, 2, 4, 7, 13, 24 ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment