pascalsTriangle.js

Codewars 알고리즘 풀이


Problem

  • Write a function that, given a depth ‘n’, returns a single-dimensional array representing Pascal's Triangle from the first to the nth level.
    • 깊이 ‘n’이 주어진다.
    • 파스칼의 삼각형을 나타내는 1차원 배열을 1부터 n번째까지 반환한다.


Pascal's Triangle
  • 이항계수를 삼각형 모양의 기하학적 형태로 나열한 것.
//       1
//     1   1
//   1   2   1
// 1   3   3   1



Solution 01

function pascalsTriangle(n) {
  let result = [];
  
  for (let i = 0; i < n; i++) {
    let row = [];
    
    for (let j = 0; j < i + 1; j++) {
      if (j === 0 || j === i) {
        row.push(1);
      } else {
        row.push(result[i - 1][j - 1] + result[i - 1][j]);
      }
    }
    result.push(row);
  }
  return result.join(',');
}

pascalsTriangle(1);  // [1]
pascalsTriangle(2);  // [1, 1, 1]
pascalsTriangle(3);  // [1, 1, 1, 1, 2, 1]
pascalsTriangle(4);  // [1, 1, 1, 1, 2, 1, 1, 3, 3, 1]


Solution 02

function pascalsTriangle(n) {
  let result = [];
  
  for (let i = 0; i < n; i++) {
    let number = 1;
    
    for (let j = 0; j <= i; j++) {
      result.push(number);
      number = (number * (i - j)) / (j + 1);
    }
  }
  return result;
}

pascalsTriangle(1);  // [1]
pascalsTriangle(2);  // [1, 1, 1]
pascalsTriangle(3);  // [1, 1, 1, 1, 2, 1]
pascalsTriangle(4);  // [1, 1, 1, 1, 2, 1, 1, 3, 3, 1]


Solution 03

function pascalsTriangle(n) {
  let result = [];
  let row = [];
  
  for (let i = 0; i < n; i++) {
    result.push((row = row.map((i, index) => i + (row[index - 1] || 0)).concat([1])));
  }
  return result.join(',').split(',');
}

pascalsTriangle(1);  // [1]
pascalsTriangle(2);  // [1, 1, 1]
pascalsTriangle(3);  // [1, 1, 1, 1, 2, 1]
pascalsTriangle(4);  // [1, 1, 1, 1, 2, 1, 1, 3, 3, 1]


Solution 04

function pascalsTriangle(n) {
  let result = [1];
  
  for (let row = 1; row < n; row++) {
    result.push(1);
    
    for (let col = 1; col < row; col++) {
      result.push(result[result.length - row - 1] + result[result.length - row]);
    }
    result.push(1);
  }
  return result;
}

pascalsTriangle(1);  // [1]
pascalsTriangle(2);  // [1, 1, 1]
pascalsTriangle(3);  // [1, 1, 1, 1, 2, 1]
pascalsTriangle(4);  // [1, 1, 1, 1, 2, 1, 1, 3, 3, 1]