Skip to content

[Algorithm] 개인정보 수집 유효기간 #67

@hwangJi-dev

Description

@hwangJi-dev

💬 문제

[코딩테스트 연습 - 개인정보 수집 유효기간](https://school.programmers.co.kr/learn/courses/30/lessons/150370)


💬 풀이

func solution(_ today:String, _ terms:[String], _ privacies:[String]) -> [Int] {
    var termDict: [String: Int] = [:]
    let today = today.components(separatedBy: ".")
    var result: [Int] = []
    
    for term in terms {
        let t = term.components(separatedBy: .whitespaces)
        termDict[t[0]] = Int(t[1])
    }
    
    for (index, privacy) in privacies.enumerated() {
        let p = privacy.components(separatedBy: .whitespaces)[1]
        var d = privacy.components(separatedBy: .whitespaces)[0].components(separatedBy: ".").compactMap{ Int(String($0)) }
        
        d[0] += termDict[p]! / 12
        d[1] += termDict[p]! % 12
        d[2] -= 1
        
        if d[1] > 12 {
            d[1] -= 12
            d[0] += 1
        }
        
        if d[2] == 0 {
            d[1] -= 1
            d[1] = d[1] == 0 ? 12 : d[1]
            d[0] -= d[1] == 0 ? 1 : 0
            d[2] = 28
        }
        
        var s = d.map({ String($0) })
        s[1] = String(format: "%02d", arguments: [d[1]])
        s[2] = String(format: "%02d", arguments: [d[2]])
        
        if today.joined() > s.joined() {
            result.append(index + 1)
        }
    }

    return result
}

💬 더 나은 방법?

func solution(_ today: String, _ terms: [String], _ privacies: [String]) -> [Int] {
    var answer = [Int]()
    var termDict = [String: Int]()
    let date = getDate(today)

    for s in terms {
        let term = s.components(separatedBy: .whitespaces)
        termDict[term[0]] = Int(term[1])
    }

    for i in privacies.indices {
        let privacy = privacies[i].components(separatedBy: .whitespaces)

        if getDate(privacy[0]) + (termDict[privacy[1]] ?? 0) * 28 <= date {
            answer.append(i + 1)
        }
    }
    return answer
}

private func getDate(_ today: String) -> Int {
    let date = today.split(separator: ".")
    let year = Int(date[0]) ?? 0
    let month = Int(date[1]) ?? 0
    let day = Int(date[2]) ?? 0
    return (year * 12 * 28) + (month * 28) + day
}

💬 알게된 문법

✅ indices

  • 배열을 안전하게 조회할 수 있는 방법

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions