CodeWars 코딩 문제 2021/01/15 - Christmas tree

이호현·2021년 1월 15일
0

Algorithm

목록 보기
53/138

[문제]

Create a function christmasTree(height) or christmas_tree(height) (in ruby, python) that returns a christmas tree of the correct height

christmasTree(5) || christmas_tree(5) should return:

Height passed is always an integer between 0 and 100.

Use \n for newlines between each line.

Pad with spaces so each line is the same length. The last line having only stars, no spaces.

[풀이]

function christmasTree(height) {
  let answer = [];

  for(let i = 1; i <= height; i++) {
    answer.push('*'.repeat(i).padStart(height, ' ') + '*'.repeat(i - 1).padEnd(height - 1, ' '));
  }

  return answer.join('\n');
}

왼쪽, 오른쪽 나눠서 문자열 계산하기로 함.
왼쪽은 *을 기준으로 왼쪽에 *을 늘려가고, 오른쪽은 빈 문자열에서 *을 오른쪽으로 하나씩 늘려감.
반복문 한번 돌때마다 이 작업을 하고, 배열에 push.
마지막에 줄바꿈 문자열 \n을 이용해 join하면 됨.

profile
평생 개발자로 살고싶습니다

0개의 댓글