본문 바로가기

algorithm/codewars

[6kyu] Tribonacci sequence

문제설명

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 and be ready for anything else which is not clearly specified ;)





나의풀이


function tribonacci(signature,n){ for(let i = 0; i < n-3; i++){ // array length starts with 3, 4, 5, 6.... n signature.push(signature.slice(i).reduce((a,b) => a + b)) // the range of sum moves } return signature.slice(0,n); // return it }



다른사람의 풀이


function tribonacci(signature,n){
for (var i = 0; i < n-3; i++) { // iterate n times signature.push(signature[i] + signature[i+1] + signature[i+2]); } // add last 3 array items and push to trib return signature.slice(0, n); //return trib - length of n }



느낀점

많이 풀어본 피보나치의 업그레이드? 버전이다. 메서드를 활용해서 금방 풀었는데 생각외로 추천이 가장 많은 풀이와 많이 유사하다. 차이점은 내 풀이를 좀 더 이해하기 쉽게 풀어썼다는 것 정도가 있겠다. 어쨌든, 간단하게 잘 푼것같다. 

'algorithm > codewars' 카테고리의 다른 글

[6kyu] Financing a purchase  (0) 2018.02.13
[6kyu] Highest Scoring  (0) 2018.02.13
[6kyu] Simple string expansion  (0) 2018.02.07
[7kyu] Homogenous array  (0) 2018.02.04
[6kyu] crashing boxes  (0) 2018.01.28