Fibonacci, Tribonacci and friends ( 6 kyu )

문제

If you have completed the Tribonacci sequence kata, you would know by now that mister Fibonacci has at least a bigger brother. If not, give it a quick look to get how things work.

Well, time to expand the family a little more: think of a Quadribonacci starting with a signature of 4 elements and each following element is the sum of the 4 previous, a Pentabonacci (well Cinquebonacci would probably sound a bit more italian, but it would also sound really awful) with a signature of 5 elements and each following element is the sum of the 5 previous, and so on.

Well, guess what? You have to build a Xbonacci function that takes a signature of X elements - and remember each next element is the sum of the last X elements - and returns the first n elements of the so seeded sequence.

xbonacci {1,1,1,1} 10 = {1,1,1,1,4,7,13,25,49,94}
xbonacci {0,0,0,0,1} 10 = {0,0,0,0,1,1,2,4,8,16}
xbonacci {1,0,0,0,0,0,1} 10 = {1,0,0,0,0,0,1,2,3,6}
xbonacci {1,1} produces the Fibonacci sequence

피보나치를 확장시켜 주어진 배열의 n번째 항까지 구해 리턴하는 문제

풀이

function Xbonacci(signature,n){
  let arr = signature.slice(), sum;
  for ( let i = 0; i < n-signature.length; i++ ) {
    sum = 0;
    for ( let j = i; j < i+signature.length; j++ ) {
      sum += arr[j]
    }
    arr.push(sum)
  }
  return arr.slice(0, n);
}

주어진 기본 배열을 복사해 다음 항은 이전 항들의 합으로 구해지도록 함

다른 사람의 풀이

const Xbonacci = (sig, n) => {
  let len = sig.length;
  for (let i = len; i < n; i++) 
    sig[i] = sig.slice(i - len).reduce((a, b) => a + b);
  return sig.slice(0, n);
}]

reduce를 사용해 이전항들의 합을 다음 항에 넣어주는 방법


'자료구조, 알고리즘 > Codewars 문제' 카테고리의 다른 글

Simple reversed parenthesis ( 6 kyu )  (0) 2018.01.09
Array Deep Count ( 6 kyu )  (0) 2017.12.27
Fibonacci, Tribonacci and friends ( 6 kyu )  (0) 2017.12.23
What is the growth? ( 6 kyu )  (0) 2017.12.22
Dashatize it ( 6 kyu )  (0) 2017.12.20
String average ( 6 kyu )  (0) 2017.12.19

+ Recent posts