tribonacci.js

Codewars 알고리즘 풀이


Problem

  • Well met with Fibonacci bigger brother, AKA Tribonacci.
    • Fibonacci의 큰 형인 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.
    • 이름에서 알 수 있듯이 Fibonacci처럼 동작한다.
    • 마지막 3개의 숫자를 더해서 다음 숫자를 생성한다.



Solution 01

function tribonacci(arr, n) {
  let result = [];
  
  for (let i = 0; i < n; i++) {
    if (i < 3) {
      result.push(arr[i]);
    } else {
      result.push(result[i - 1] + result[i - 2] + result[i - 3]);
    }
  }
  return result;
}

tribonacci([0, 0, 0], 10);  // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
tribonacci([0, 0, 1], 10);  // [0, 0, 1, 1, 2, 4, 7, 13, 24, 44]
tribonacci([1, 1, 1], 10);  // [1, 1, 1, 3, 5, 9, 17, 31, 57, 105]
tribonacci([1, 2, 3], 10);  // [1, 2, 3, 6, 11, 20, 37, 68, 125, 230]


Solution 02

function tribonacci(arr, n) {
  let result = [];
  
  for (let i = 0; i < n; i++) {
    result.push(i < 3 ? arr[i] : result[i - 1] + result[i - 2] + result[i - 3]);
  }
  return result;
}

tribonacci([0, 0, 0], 10);  // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
tribonacci([0, 0, 1], 10);  // [0, 0, 1, 1, 2, 4, 7, 13, 24, 44]
tribonacci([1, 1, 1], 10);  // [1, 1, 1, 3, 5, 9, 17, 31, 57, 105]
tribonacci([1, 2, 3], 10);  // [1, 2, 3, 6, 11, 20, 37, 68, 125, 230]


Solution 03

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

tribonacci([0, 0, 0], 10);  // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
tribonacci([0, 0, 1], 10);  // [0, 0, 1, 1, 2, 4, 7, 13, 24, 44]
tribonacci([1, 1, 1], 10);  // [1, 1, 1, 3, 5, 9, 17, 31, 57, 105]
tribonacci([1, 2, 3], 10);  // [1, 2, 3, 6, 11, 20, 37, 68, 125, 230]


Solution 04

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

tribonacci([0, 0, 0], 10);  // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
tribonacci([0, 0, 1], 10);  // [0, 0, 1, 1, 2, 4, 7, 13, 24, 44]
tribonacci([1, 1, 1], 10);  // [1, 1, 1, 3, 5, 9, 17, 31, 57, 105]
tribonacci([1, 2, 3], 10);  // [1, 2, 3, 6, 11, 20, 37, 68, 125, 230]


Solution 05

function tribonacci(arr, n) {
  const result = arr.slice(0, n);
  
  while (result.length < n) {
    result[result.length] = result.slice(-3).reduce((total, i) => total + i, 0);
  }
  return result;
}

tribonacci([0, 0, 0], 10);  // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
tribonacci([0, 0, 1], 10);  // [0, 0, 1, 1, 2, 4, 7, 13, 24, 44]
tribonacci([1, 1, 1], 10);  // [1, 1, 1, 3, 5, 9, 17, 31, 57, 105]
tribonacci([1, 2, 3], 10);  // [1, 2, 3, 6, 11, 20, 37, 68, 125, 230]