Notice
Recent Posts
Recent Comments
Link
study record
백준 1292 - 스위프트 풀이 본문
import Foundation
func BJ1292(){
let nums = readLine()!.split(separator: " ").map{ Int($0)}
var arr: [Int] = []
var count = 1
var n = 1
for _ in 1...1000 {
arr.append(n)
if count < n {
count += 1
}else{
n += 1
count = 1
}
}
var sum = 0
for i in nums[0]!...nums[1]! {
sum += arr[i-1]
}
print(sum)
}
func BJ1292plus(){
// 더 깔끔한 풀이
var arr: [Int] = []
for i in 1..<50 {
arr.append(contentsOf: [Int](repeating: i, count: i))
}
let input = readLine()!.split(separator: " ").map { Int($0)! - 1 }
print(arr[input[0]...input[1]].reduce(0, +))
}
배열의 끝에 원소를 넣는 메서드인 append()를 활용한다. append(contentsOf: )를 활용하여 하나의 원소가 아닌 컨텐츠를 넣을 수 있다.
init(repeating:count:)를 활용하여 원하는 원소를 원하는 횟수만큼 새 배열을 만들 수 있다.
let fiveZs = Array(repeating: "Z", count: 5)
print(fiveZs)
// Prints "["Z", "Z", "Z", "Z", "Z"]"
https://developer.apple.com/documentation/swift/array/1641692-init/
'알고리즘 > 스위프트 알고리즘' 카테고리의 다른 글
백준 2740 - 스위프트 풀이 (0) | 2022.02.06 |
---|---|
백준 9093 - 스위프트 풀이 (0) | 2022.02.03 |