티스토리 뷰

728x90
반응형

https://programmers.co.kr/learn/courses/30/lessons/12969

 

코딩테스트 연습 - 직사각형 별찍기

이 문제에는 표준 입력으로 두 개의 정수 n과 m이 주어집니다. 별(*) 문자를 이용해 가로의 길이가 n, 세로의 길이가 m인 직사각형 형태를 출력해보세요. 제한 조건 n과 m은 각각 1000 이하인 자연수

programmers.co.kr

 


 

<나의 풀이>

import Foundation

let n = readLine()!.components(separatedBy: [" "]).map { Int($0)! }
let (a, b) = (n[0], n[1])

// 별을 넣어 주기 위해 빈 배열 생성
var stars = [String]()

// a(가로)의 길이만큼 배열에 별을 넣어 줌
for _ in 1...a {
    stars.append("*")
}

// 배열안의 요소들을 한줄의 문자열로 만든 후, 출력 
// b(세로)의 길이만큼 반복함
for _ in 1...b {
    let result = stars.joined()
    print(result)
}

 


 

<다른 사람의 풀이>

 

import Foundation

let n = readLine()!.components(separatedBy: [" "]).map { Int($0)! }
let (a, b) = (n[0], n[1])

for _ in 0..<b {
    print(Array(repeating: "*", count: a).joined())
}

- init(repeating:count:): repeating에 반복할 요소를, count에 반복 횟수를 넣어주면 됨

 

import Foundation

let n = readLine()!.components(separatedBy: [" "]).map { Int($0)! }
let (a, b) = (n[0], n[1])

let x = String(repeating: "*", count: a)
for i in 1...b {
    print(x)
}

init(repeating:count:): repeating에 반복할 문자열을, count에 반복 횟수를 넣어주면 됨

 

import Foundation

let n = readLine()!.components(separatedBy: [" "]).map { Int($0)! }
let (a, b) = (n[0], n[1])

var star = ""

for _ in 0 ..< a{
    star.append("*")
}

for _ in 0 ..< b{
    print(star)
}

- 문자열도 append 메서드 사용 가능

728x90
반응형
댓글