Description:
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 ;)
If you enjoyed this kata more advanced and generalized version of it can be found in the Xbonacci kata
[Personal thanks to Professor Jim Fowler on Coursera for his awesome classes that I really recommend to any math enthusiast and for showing me this mathematical curiosity too with his usual contagious passion :)]
function tribonacci(signature, n) {
let numArr = signature;
if (n < 4) {
return signature.slice(0, n);
} else {
for (i=0; i < n-3; i++) {
numArr.push((numArr[i] + numArr[i+1] + numArr[i+2]));
}
return numArr;
}
}
먼저 배열인 signature를 numArr로 선언해주었다.
만약에 n이 4 미만인 경우에 signature 배열을 배열의 0번째 자리부터 n번째 자리까지 slice한 것을 리턴해주기로 했다.
그렇지 않은 경우에는 i를 n-3번까지 반복을 시키면서 numArr의 0번째 1번째 2번째 수를 더하고 1번째 2번째 3번째 수를 더하는 형식으로 코드를 작성하였다.
이를 push()를 사용해서 새로운 배열이 되게끔 해주었으니 numArr를 리턴해주면 된다.
'코테연습' 카테고리의 다른 글
35.Unique In Order (0) | 2022.04.09 |
---|---|
34.Decode the Morse code (0) | 2022.04.08 |
32.Your order, please (0) | 2022.04.07 |
31.Replace With Alphabet Position (0) | 2022.04.07 |
30.Persistent Bugger. (0) | 2022.04.04 |
댓글