플랫폼 | 번호 | 제목 | 유형 | 난이도 | 언어 |
---|---|---|---|---|---|
프로그래머스 | 150370 | 개인정보 수집 유효기간 | 시뮬레이션 | Lv.1 | Swift |
단순히 주어진 요구사항을 구현하는 문제이다.
효율적인 날짜 계산 방법만 떠올리면 어렵지 않게 해결할 수 있다.
이번에는 날짜를 모두 '일'로 변환하여 계산했다.
년*12*28 + 월*28 + 일
이렇게 변환하면 간단하게 대소 비교로 각 날짜를 비교할 수 있다.
import Foundation
func solution(_ today:String, _ terms:[String], _ privacies:[String]) -> [Int] {
func dateToInt(_ date: String) -> Int {
let temp = date.split(separator: ".").map{ Int($0)! }
return temp[0]*12*28 + temp[1]*28 + temp[2]
}
let todayDate = dateToInt(today)
var termsDic: [String:Int] = [:]
for term in terms {
let input = term.split(separator: " ")
termsDic[String(input[0])] = Int(input[1])! * 28
}
var result: [Int] = []
for (i, privacie) in privacies.enumerated() {
let input = privacie.split(separator: " ").map{ String($0) }
let (collectionDate, type) = (dateToInt(input[0]), input[1])
if collectionDate + termsDic[type]! <= todayDate {
result.append(i+1)
}
}
return result
}
개선 전에는 아래와 같이 날짜 연, 월, 일을 따로 계산했다. 그러다 보니 계산이 복잡해지고 코드가 불필요하게 복잡해졌다.
알고리즘 문제에서 날짜 계산이 나오면 하나의 단위로 변환하는 것을 먼저 고려해 보자!
import Foundation
func solution(_ today:String, _ terms:[String], _ privacies:[String]) -> [Int] {
func dateStringToIntArray(_ date: String) -> [Int] {
return date.split(separator: ".").map{ Int($0)! }
}
let todays = dateStringToIntArray(today)
var termss: [String:Int] = [:]
for term in terms {
let input = term.split(separator: " ")
termss[String(input[0])] = Int(input[1])!
}
func calculateDate(_ date: [Int], _ add: Int) -> [Int] {
var newDate = Array(repeating: 0, count: 3)
let addY = add/12
let addM = add%12
newDate[0] = date[0] + addY
newDate[1] = date[1] + addM
newDate[2] = date[2] - 1
if newDate[1] > 12 {
newDate[0] = newDate[0] + 1
newDate[1] -= 12
}
if newDate[2] < 1 {
newDate[1] = newDate[1] - 1
if newDate[1] == 0 {
newDate[1] = 12
}
newDate[2] = 28
}
return newDate
}
func isDateOver(_ today: [Int], _ past: [Int], _ type: String) -> Bool {
let date = calculateDate(past, termss[type]!)
if date[0] < today[0] { return true }
else if date[0] == today[0] && date[1] < today[1] { return true }
else if date[0] == today[0] && date[1] == today[1] && date[2] < today[2] { return true }
else { return false }
}
var result: [Int] = []
for (i, privacie) in privacies.enumerated() {
let input = privacie.split(separator: " ").map{ String($0) }
let (past, type) = (dateStringToIntArray(input[0]), input[1])
if isDateOver(todays, past, type) {
result.append(i+1)
}
}
return result
}