# Enhanced Fibonacci function Tribonacci

Keywords: Java less

It's nice to meet the bigger brother of Fibonacci, AKA Tribonacci.
It is basically like Fibonacci, but the last three (rather than two) numbers of the sequence are combined to generate the next one.
So, if we want to start our Tribonacci sequence with the start [1, 1, 1] input, we have the following sequence:

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

We will start to modify the relation with [0, 0, 1] as follows:

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

You need to create a Fibonacci function that gives an array / list and returns the first n elements - all sequences.
The input array always contains 3 numbers; n will always be non negative; if n == 0, then an empty array is returned.
At the same time, we should pay attention to the situation of 0 < n < 3.

# My solution

``````  public  double[] tribonacci(double[] s, int n) {
double[] b = new double[n];

// If the length is less than 3, the incoming data is traversed and the corresponding length array is returned
if (n < 3) {
for (int i = 0; i < n; i++) {
b[i] = s[i];
}
return b;
}

// First, put the first three bits in the new array
if (s != null && s.length > 0) {
for (int i = 0; i < s.length; i++) {
b[i] = s[i];
}

// Traverse and put the value of length minus 3 into the new array
for (int i = s.length; i < n; i++) {
double first = b[i - 3];
double second = b[i - 2];
double thrid = b[i - 1];
b[i] = (first + second + thrid);

}
}
return b;
}``````

1.

``````import java.util.Arrays;

public class Xbonacci {
public double[] tribonacci(double[] s, int n) {

double[] tritab=Arrays.copyOf(s, n);
for(int i=3;i<n;i++){
tritab[i]=tritab[i-1]+tritab[i-2]+tritab[i-3];
}
return tritab;

}
}``````

2.

``````import java.util.Arrays;

public class Xbonacci {
public double[] tribonacci(double[] s, int n) {

double[] tritab=Arrays.copyOf(s, n);
for(int i=3;i<n;i++){
tritab[i]=tritab[i-1]+tritab[i-2]+tritab[i-3];
}
return tritab;

}
}``````

3.

``````public class Xbonacci {

public double[] tribonacci(double[] s, int n) {
// hackonacci me
if( n == 0 )
return new double[0];
double[] res = new double[n];
for( int i = 0; i < n; i++ ) {
if( i < 3 )
res[i] = s[i];
else
res[i] = res[i-1]+res[i-2]+res[i-3];
}
return res;
}
}``````