[프로그래머스] 주차 요금 계산(Kotlin)
풀이
- 00:00부터 23:59까지의 입/출차 내역을 바탕으로
차량별 누적 주차 시간을 계산하여
요금을 일괄로 정산함에 주의!!
import kotlin.math.*
class Solution {
fun solution(fees: IntArray, records: Array<String>): IntArray {
val inTimeMap:MutableMap<String, Int> = mutableMapOf()
val parkTimeMap:MutableMap<String, Int> = mutableMapOf()
val feeMap:MutableMap<String, Int> = mutableMapOf()
records.map{it.split(" ")}.forEach{ record ->
val time = record[0]
val carNum = record[1]
val history = record[2]
if(history == "IN"){
inTimeMap[carNum] = timeToInt(time)
}
else{
val inTime = inTimeMap[carNum]!!
val outTime = timeToInt(time)
val curParkTime = outTime - inTime
var prevParkTime = 0
if(parkTimeMap.containsKey(carNum)){
prevParkTime = parkTimeMap[carNum]!!
parkTimeMap.remove(carNum)
}
parkTimeMap[carNum] = prevParkTime + curParkTime
inTimeMap.remove(carNum)
}
}
inTimeMap.toList().forEach{
val carNum = it.first
val inTime = it.second
val outTime = timeToInt("23:59")
val curParkTime = outTime - inTime
var prevParkTime = 0
if(parkTimeMap.containsKey(carNum)){
prevParkTime = parkTimeMap[carNum]!!
parkTimeMap.remove(carNum)
}
parkTimeMap[carNum] = prevParkTime + curParkTime
}
parkTimeMap.toList().forEach{
val carNum = it.first
val totalParkTime = it.second
feeMap[carNum] = calcFee(totalParkTime, fees)
}
var answer = feeMap.toList().sortedBy{it.first}.map{it.second}
return answer.toIntArray()
}
private fun timeToInt(time:String):Int{
val h = time.substring(0,2).toInt()
val m = time.substring(3).toInt()
return h*60 + m
}
private fun calcFee(parkTime:Int, fees:IntArray):Int{
val basicTime = fees[0].toInt()
val basicFee = fees[1].toDouble()
val unitTime = fees[2].toInt()
val unitFee = fees[3].toDouble()
var fee: Double = basicFee
if(parkTime > basicTime)
fee += ceil((parkTime-basicTime).toDouble()/unitTime) * unitFee
println("parkTime: ${parkTime}, fee: ${fee}")
return fee.toInt()
}
}