💡 학습 포인트
- 입력 처리 및 검증
- readLine()과 guard 문을 사용하여 입력받은 데이터를 안전하게 처리하는 방법을 익혔습니다.
- 조건 분기
- 게임 종류에 따라 필요한 추가 인원수를 결정하기 위해 if-else 구문을 사용했습니다.
- 중복 제거
- Set<String> 자료구조를 활용하여, 신청한 사람들의 중복된 이름을 효율적으로 제거할 수 있음을 배웠습니다.
- 함수 분리
- main() 함수를 도입해 코드의 가독성과 구조를 개선하고, exit(0) 대신 안전한 조기 반환 방식을 적용했습니다.
⚙️ Swift 코드 예제
func main() {
if let firstLine = readLine() {
let inputs = firstLine.split(separator: " ")
guard inputs.count == 2, let n = Int(inputs[0]) else { return }
let gameType = String(inputs[1])
let additionalPlayersNeeded: Int
if gameType == "Y" {
additionalPlayersNeeded = 1
} else if gameType == "F" {
additionalPlayersNeeded = 2
} else if gameType == "O" {
additionalPlayersNeeded = 3
} else {
print(0)
return
}
var participants = Set<String>()
for _ in 0..<n {
if let name = readLine() {
participants.insert(name)
}
}
let maxPlays = participants.count / additionalPlayersNeeded
print(maxPlays)
}
}
main()
🤔 느낀 점
- 안전한 입력 처리와 옵셔널 바인딩의 중요성을 다시 한번 깨달았습니다.
- Set 자료구조를 통한 중복 제거가 간결하면서도 효율적인 해결 방법임을 확인했습니다.
- 함수를 분리하여 코드를 모듈화하는 습관이 유지보수와 확장성 측면에서 유리함을 느꼈습니다.
반응형
'알고리즘' 카테고리의 다른 글
| 백준 29723번 문제 풀이 (0) | 2025.04.18 |
|---|---|
| 백준 1181번 문제 풀이 (0) | 2025.04.17 |
| leetcode 187. Repeated DNA Sequences (0) | 2025.04.15 |
| 백준 2358번 평행선 문제 풀이 (0) | 2025.04.14 |
| leetcode 706. Design HashMap (0) | 2025.04.10 |