본문 바로가기
알고리즘/Codewars

[Codewars] Build Tower (6 kyu) / JavaScript

by fluss 2022. 11. 11.

https://www.codewars.com/kata/576757b1df89ecf5bd00073b

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Build Tower

Build a pyramid-shaped tower, as an array/list of strings, given a positive integer number of floors. A tower block is represented with "*" character.

For example, a tower with 3 floors looks like this:

[
  "  *  ",
  " *** ", 
  "*****"
]

And a tower with 6 floors looks like this:

[
  "     *     ", 
  "    ***    ", 
  "   *****   ", 
  "  *******  ", 
  " ********* ", 
  "***********"
]

 

Go challenge Build Tower Advanced once you have finished this :)

 

설명:

탑 만들기

층의 숫자가 양의 정수로 주어지면, 피라미드 모양의 탑을 문자열의 배열/리스트로 만드세요. 탑 블록은 '*'문자로 표현됩니다.

예를 들어, 3층 탑은 다음과 같습니다:

[
  "  *  ",
  " *** ", 
  "*****"
]

그리고 6층 탑은 다음과 같습니다.

[
  "     *     ", 
  "    ***    ", 
  "   *****   ", 
  "  *******  ", 
  " ********* ", 
  "***********"
]

 

이것이 끝나면 Build Tower Advanced에 도전해보세요 :)

 

풀이

탑의 '*'개수는 1부터 3, 5, 7,... 이런 식으로 2개씩 늘어난다. 그래서 반복문을 i는 1일 때부터 시작해 (i - 1) * 2 + 1 만큼 repeat으로 반복시켰다. 그리고 공백은 밑변의 길이가 탑의 높이보다 하나 작은 직각 삼각형이기 때문에 입력받은 층수에서 i를 뺀 만큼의 공백을 repeat으로 반복시키고 그것을 탑 앞뒤로 붙여주었다.

 

코드

function towerBuilder(nFloors) {
  let result = [];
  for(let i = 1; i <= nFloors; i++){
    let str = ""
    str += " ".repeat(nFloors - i) + "*".repeat((i - 1) * 2 + 1) + " ".repeat(nFloors - i);
    result.push(str);
  }
  return result
}

댓글