문제

It is not hard to draw a triangle of stars of any given size. For example, a size 5 triangle would look like this (5 stars high and 5 stars wide):

*
**
***
****
*****

Your task is to draw triangles in a number of sizes. 

 

 

입력

Each line of input contains a single positive integer, n, 1 <= n <= 100. The last line of input contains 0. For each non-zero number, draw a triangle of that size. 

 

 

출력

Output consists of triangles of the appropriate sizes. Each triangle is wider at the bottom. There are no gaps between the triangles.

 

 

풀이

별 찍기 문제처럼 별을 찍는 문제지만 여러개의 테스트케이스가 있는 것을 볼 수 있다.

각각의 테스트케이스를 for문을 통해 순회하며 

각각의 내부에서 다시 이중 for문을 통해 문제를 해결할 수 있다.

 

또는 인쇄를 담당하는 함수를 추가로 생성한 다음 결과값만을 처리하는 방법도 가능하고

테스트케이스의 숫자가 정해져 있지 않은 문제는 출력을 한번에 하는 습관을 들이는 것이 좋다.

 

또한 예전 코드를 보니 const가 아닌 let으로 처리하는 내용이 많이 보이는데

상수 또는 배열이나 객체를 다룰 때는 const를 사용해 안정성을 유지하는 것이 좋다.

const input = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n').map(Number)

const result = []
for(let i = 0 ; i < input.length-1 ; i++){
    for(let j = 1 ; j <= input[i] ; j++){
        result.push('*'.repeat(j))
    }
}

console.log(result.join('\n'))
const input = `5
3
2
7
0`.split('\n').map(Number)

const result = []
for(let i = 0 ; i < input.length-1 ; i++){
    for(let j = 1 ; j <= input[i] ; j++){
        result.push('*'.repeat(j))
    }
}

console.log(result.join('\n'))

'알고리즘 > 백준' 카테고리의 다른 글

[백준 JS] 11720번 숫자의 합  (0) 2023.03.09
[백준 JS] 10808번 알파벳 개수  (0) 2023.03.09
[백준 JS] 3046번 R2  (0) 2023.03.09
[백준 JS] 2845번 파티가 끝나고 난 뒤  (0) 2023.03.09
[백준 JS] 2742번 기찍 N  (0) 2023.03.09

+ Recent posts