본문 바로가기
알고리즘

[Swift 알고리즘] 프로그래머스 lv2 - 주차 요금 계산

by 코코종 2022. 3. 15.
728x90

 

 

안녕하세요 코코종입니다! 이번에도 2022년 카카오 공채 문제네요!

문제를 풀수록 뭔가 점점 실력이 발전하고 있는 것 같은 기분이 드네요 호호..(아님 말구...)



https://programmers.co.kr/learn/courses/30/lessons/92341

 

코딩테스트 연습 - 주차 요금 계산

[180, 5000, 10, 600] ["05:34 5961 IN", "06:00 0000 IN", "06:34 0000 OUT", "07:59 5961 OUT", "07:59 0148 IN", "18:59 0000 IN", "19:09 0148 OUT", "22:59 5961 IN", "23:00 5961 OUT"] [14600, 34400, 5000]

programmers.co.kr

import Foundation

func calculateTime(_ inTime: String, _ outTime: String) -> Int {
    let inComponents = inTime.components(separatedBy: ":")
    let inHour = Int(inComponents[0])!
    let inMin = Int(inComponents[1])!
    
    let outComponents = outTime.components(separatedBy: ":")
    let outHour = Int(outComponents[0])!
    let outMin = Int(outComponents[1])!
    
    let result = (60*outHour + outMin) - (60*inHour + inMin)
    return result
}

func calculateFee(_ useTime: Int, _ baseTime: Int, _ baseFee: Int, _ extraTime: Int, _ extraFee: Int) -> Int {
    
    if useTime <= baseTime {
        return baseFee
    } else {
        // extraTime -1 을 더해줌으로써 올림처리
        var result = (useTime - baseTime + extraTime - 1)/extraTime * extraFee + baseFee
        return result   
    }
}

func solution(_ fees:[Int], _ records:[String]) -> [Int] {
    
    // 차량 번호가 작은 자동차부터 청구할 주차 요금을 차례대로 정수 배열에 담아서 return
    // 아직 출차하지 않은 차량은 23:59분에 출차한 것으로 간주
    
    // 차량 번호 : 들어온 시간
    var inDict: [String: String] = [:]
    // 차랑번호 : 총 이용시간
    var timeDict: [String:Int] = [:]
    
    for rec in records {
        let components = rec.components(separatedBy: " ")
        let time = components[0]
        let car = components[1]
        // let action = components[2]
        // 이렇게 하면 action에 대한 처리를 안해줘도 될 듯
        
        // 아직 안들어왔거나 나갔거나
        if inDict[car] == nil {
            inDict[car] = time
            if timeDict[car] == nil { // 미이용
                timeDict[car] = 0
            } else { // 재출입
                timeDict[car]! += 0
            }
        } else {
            timeDict[car]! += calculateTime(inDict[car]!, time)
            inDict[car] = nil
        }
    }
    
    // 아직 나가지 않은 차량 계산
    inDict.forEach {
        timeDict[$0.key]! += calculateTime($0.value, "23:59")
        // print("미출차",timeDict)
    }
    
    // 차량번호 오름차순 정렬
    let sortedTimeDict = timeDict.sorted(by: < )
    // print(sortedTimeDict)
    
    var result: [Int] = []
    sortedTimeDict.forEach {
        result.append(calculateFee($0.value, fees[0], fees[1], fees[2], fees[3]))
    }
    
    return result
}

 


 

차량별로 들어온 시간과 이용시간 2개의 dictionary 생성해서 처리를 해줬습니다. In과 Out에 대한 처리를 하려고 했는데 Out이 되면 dictionary의 value를 초기화 해줬습니다. 이후 dictionary의 value값이 있다면 23시 59분에 출차한 처리를 해줬습니다.

이용요금을 계산하는 과정에서 올림처리가 필요했는데 (extraTime -1)을 더해줘서 해결했습니다. 나머지가 있다면 +1을 해주는 방법도 있겠네요!

 

딕셔너리를 자주 쓰다보니 익숙해진 것 같네요! 그래서 배열로 처리하는 것보다 빨라져서 기분이 좋습니다!(그래서 쫌 성장했다고 느낍니다)

그럼 이만!

728x90