본문 바로가기
알고리즘/Codewars

[Codewars] Tribonacci Sequence (6 kyu) / JavaScript

by fluss 2022. 12. 9.

https://www.codewars.com/kata/556deca17c58da83c00002db

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

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 :)]

 

설명:

피보나치의 형, 일명 트리보나치와 잘 만났습니다.

 

이름에서 이미 드러났듯이, 기본적으로 피보나치와 같이 작동하지만 수열의 마지막 3개 (2개 대신) 숫자를 합하여 다음 수를 생성합니다. 그리고 더 나쁜 부분은, 유감스럽게도 이탈리아어가 모국어가 아닌 사람들이 이것을 발음하려 하는 것을 들을 수 없다는 것입니다 :(

 

그래서,  [1, 1, 1]을 시작 입력(일명 초기값)으로 트리보나치 수열을 시작하면 우리는 다음과 같은 수열을 가지게 됩니다:

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

 

하지만 [0, 0, 1]을 초기값으로 시작한다면 어떨까요? [1, 1] 대신 [0, 1]로 시작하면 일반적인 피보나치 수열이 기본적으로  한 자리씩 이동되므로 두 자리씩 이동된 같은 수열을 얻을 거라고 생각할 수 있지만 그것은 우리가 얻게 되는 경우가 아닙니다:

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

 

아마 지금쯤이면 짐작했을지 모르지만 확실히 하자면, 주어진 초기값 배열/리스트를 받아 초기값을 포함한 처음 n개의 원소를 반환하는 피보나치 함수를 만들어야 합니다.

 

초기값은 항상 3개의 숫자를 포함하고 있으며, n은 언제나 음의 정수가 아닙니다. 만약 n == 0라면, 빈 배열을 반환하고 (C에서는 NULL을 반환) 명확하게 지정되지 않은 다른 모든 사항에 대비합니다 ;)

 

이 kata를 즐겼다면 Xbonacci kata에서 더 발전되고 일반적인 버전을 찾을 수 있습니다.

 

[모든 수학 애호가들에게 정말 추천하는 멋진 수업과 그의 전염성이 강한 열정으로 나에게 수학적 호기심을 보여준 것에 대해 Coursera의 Jim Fowler 교수에게 개인적으로 감사드립니다 :)]

 

풀이

n이 0이라면 빈 배열을 반환 그리고 n이 3보다 작다면 signature를 n의 길이만큼 잘라서 반환해주었다. 그리고 나머지 경우는 반복문으로 n의 크기만큼 i의 전 값 3개를 더한 값을 배열에 넣어주고 그 배열을 반환했다.

 

코드

function tribonacci(signature,n){
  if(n === 0) return [];
  if(n < 3) return signature.slice(0, n);
  const tri = signature;
  
  for(let i = 3; i < n; i++){
    tri.push(tri[i - 1] + tri[i - 2] + tri[i - 3]);
  }
  return tri
}

댓글