[알고리즘] Swift -프로그래머스 연습문제 #150370(2023 카카오 블라인드_개인정보 수집 유효기간)

2023. 5. 22. 18:13ALGORITHM/Swift

728x90
반응형

문제링크

 

 

 

 

분석

1~n번으로 분류된 개인정보 n개가 있다. 

약관마다 유효기간이 정해져있다. 

오늘 날짜로 파기해야 할 개인정보 번호들을 구하려고 한다.

모든 달은 28일까지 있다고 가정한다.

예를 들어 A라는 약관의 유효기간이 12달이고 2021년 01월 05일에 수집되었다면 2022년 01월 04일까지 보관가능하고 2022년 01월 05일부터는 파기해야할 개인정보이다.

 

오늘 날짜와 유효기간을 담은 배열과 수집된 개인정보의 정보를 담은 배열이 주어질 때 파기해야 할 개인정보의 번호를 오름차순으로 리턴하는 문제이다.

 

 

풀이 과정

개인정보를 담은 배열만큼 반복을 한 후 그에 해당하는 약관의 유효기간을 오늘 날짜와 비교한다.

먼저 String 형태로 주어지는 날짜를 Date형식으로 변환한다.

extension String {
    func toDate() -> Date? { //"yyyy-MM-dd HH:mm:ss"
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy.MM.dd"
        dateFormatter.timeZone = TimeZone(identifier: "ko")
        if let date = dateFormatter.date(from: self) {
            return date
        } else {
            return nil
        }
    }
}

 

split을 통해 주어진 배열에서 " "를 구분하여 약관별 유효기간을 Dictionary에 저장한다.

var dic = [String: Int]()
for term in terms {
    let split = term.split(separator: " ").map({ String($0) })
    dic[split[0]] = Int(split[1])
}

 

그 후 개인정보의 날짜와 오늘 날짜를 비교하여 차이를 계산한다.

for i in 0..<privacies.count {
    let date = privacies[i].split(separator: " ").map({ String($0) })

    //차이 계산
    let dist = Calendar.current.dateComponents([.month], from: date[0].toDate()!, to: today.toDate()!)

    if dist.month! >= dic[date[1]]! {
        result.append(i+1)
    }
}

비교했을 때 약관별 유효기간보다 크면 기간이 만료되었다는 뜻이므로 결과롤 반환해준다.

 

 

풀이

import Foundation

func solution(_ today:String, _ terms:[String], _ privacies:[String]) -> [Int] {
    var result = [Int]()
    
    var dic = [String: Int]()
    for term in terms {
        let split = term.split(separator: " ").map({ String($0) })
        dic[split[0]] = Int(split[1])
    }
    
    for i in 0..<privacies.count {
        let date = privacies[i].split(separator: " ").map({ String($0) })
        
        let dist = Calendar.current.dateComponents([.month], from: date[0].toDate()!, to: today.toDate()!)
        
        if dist.month! >= dic[date[1]]! {
            result.append(i+1)
        }
    }
    
    return result
}

extension String {
    func toDate() -> Date? { //"yyyy-MM-dd HH:mm:ss"
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy.MM.dd"
        dateFormatter.timeZone = TimeZone(identifier: "ko")
        if let date = dateFormatter.date(from: self) {
            return date
        } else {
            return nil
        }
    }
}

 

결과

print(solution(  "2022.05.19"         , ["A 6", "B 12", "C 3"]         , ["2021.05.02 A", "2021.07.01 B", "2022.02.19 C", "2022.02.20 C"]           ))
//print(solution("2020.01.01"      , ["Z 3", "D 5"]     , ["2019.01.01 D", "2019.11.15 Z", "2019.08.02 D", "2019.07.01 D", "2018.12.28 Z"]       ))

 

 


📂  정리

Date 타입을 String으로 변환하는 방법

날짜의 차이를 계산하는 방법

 

 

 

 

 

 

728x90
반응형