buildTower.js

Codewars 알고리즘 풀이


Problem

  • Build Tower by the following given argument: number of floors (integer and always greater than 0)
    • 주어진 인수로 Tower를 건설한다.
    • 층수는 정수이며, 항상 0보다 크다.


For example: 3 floors
[
  '  *  ',
  ' *** ',
  '*****'
];


For example: 6 floors
[
  '        *        ',
  '       ***       ',
  '      *****      ',
  '    *********    ',
  '  *************  ',
  '*****************'
];



Solution 01

function buildTower(n) {
  let result = [];
  
  for (let i = 1; i <= n; i++) {
    result.push(' '.repeat(n - i) + '*'.repeat(i * 2 - 1) + ' '.repeat(n - i));
  }
  return result;
}

buildTower(1);  // ['*']
buildTower(2);  // [' * ', '***']
buildTower(3);  // ['  *  ', ' *** ', '*****']


Solution 02

function buildTower(n) {
  let result = [];
  
  for (let i = 1; i <= n; i++) {
    let space = ' '.repeat(n - i);
    let star = '*'.repeat(i * 2 - 1);
    result.push(`${space}${star}${space}`);
  }
  return result;
}

buildTower(1);  // ['*']
buildTower(2);  // [' * ', '***']
buildTower(3);  // ['  *  ', ' *** ', '*****']