DAY 5
0

## 強敵！費波那契數的哥哥登場，Ruby 30 天刷題修行篇第五話

（特此註明：題目來源是Codewars

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 (except in C return NULL) and be ready for anything else which is not clearly specified ;)

1.`n == 0`，即回傳一個空陣列；

2.`n > 0 && n < 3`，即 n 不等於 0 但小於 signature 長度的情況下，把 signature 中的元素取出再 push 進新陣列 result，比如 signature = [0, 1, 2] 而 n = 2，即回傳 [0, 1]，這裡我用了 0.upto() 方法，達到迴圈的效果。

3.`n >= 3`，首先`0.upto(2) {|i| result.push(signature[i]) }`將 signature 中，代表前三項數字的 3 個元素 push 進 result，然後數列第四項以後的數字，使用`result[i] + result[i+1] + result[i+2]`方式計算，其含意就是把數列中，最尾巴的 3 個數字相加，再將結果 push 進 result。

``````def tribonacci(signature,n)
result = []
if n == 0
result
elsif n > 0 && n < 3
0.upto(n - 1) {|i| result.push(signature[i]) }
result
else
0.upto(2) {|i| result.push(signature[i]) }
0.upto(n - 4) {|i| result.push(result[i] + result[i+1] + result[i+2]) }
result
end
end
``````

``````def tribonacci(s, n)
for i in 3..n
s[i] = s[i-1] + s[i-2] + s[i-3]
end
return s.slice(0, n)
end
``````