ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์ฃผ์ฐจ ์š”๊ธˆ ๊ณ„์‚ฐ(Swift)

2022. 10. 18. 00:38ใ†ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-Swift

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์ฃผ์ฐจ ์š”๊ธˆ ๊ณ„์‚ฐ(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

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

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

 ๋‚˜์˜ ํ’€์ด

 

๋ฌธ์ œ๋ฅผ ํ’€๋ฉด์„œ ์•Œ๊ฒŒ๋œ ์ ์€ ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ for๋ฌธ ๋Œ๋ฉด ํŠœํ”Œํ˜•ํƒœ๋กœ key์™€ value๊ฐ€ ์ƒ๊ธด๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.

์ด ์ ์„ ์ด์šฉํ•ด์„œ ๋ฌธ์ œ๋ฅผ ํ’€์–ด๋‚ด๋ฉด ๋œ๋‹ค.

 

import Foundation

func solution(_ fees:[Int], _ records:[String]) -> [Int] {
    
    func calculate(_ minute: Int) -> Int {
        if minute <= fees[0] {
            return fees[1]
        } else {
            let price = fees[1] + Int(ceil(Double(minute - fees[0]) / Double(fees[2]))) * fees[3]
            return price
        }
    }
    
    var resultDic: [String: Int] = [:]
    var timeDic: [String: String] = [:]
    
    for record in records {
        let res = record.components(separatedBy: " ")
        let time = res[0], carNum = res[1], signal = res[2]
        if timeDic[carNum] != nil && signal == "OUT" {
            let inTimeArr = timeDic[carNum]!.components(separatedBy: ":")
            let inHour = Int(inTimeArr[0])!, inMinute = Int(inTimeArr[1])!
            let outTimeArr = time.components(separatedBy: ":")
            let outHour = Int(outTimeArr[0])!, outMinute = Int(outTimeArr[1])!
            let accTime = (outHour - inHour) * 60 + (outMinute - inMinute)
            if resultDic[carNum] != nil {
                resultDic[carNum]! += accTime 
            } else {
                resultDic[carNum] = accTime
            }
            timeDic[carNum] = nil
        } else {
            timeDic[carNum] = time
        }
    }
    print(timeDic)
    for x in timeDic {
        print(x)
        let inTime = x.1.components(separatedBy: ":") 
        let inHour = Int(inTime[0])!, inMinute = Int(inTime[1])!
        let outHour = 23, outMinute = 59
        let accTime = (outHour - inHour) * 60 + (outMinute - inMinute)
        if resultDic[x.0] != nil {
            resultDic[x.0]! += accTime    
        } else {
            resultDic[x.0] = accTime
        }
        timeDic[x.0] = nil 
    }
    let arr = resultDic.sorted(by: <).map{ $0.value }
    
    return arr.map{ calculate($0) }
}