https://school.programmers.co.kr/learn/courses/30/lessons/92341
주차장의 요금표와 차량이 들어오고(입차) 나간(출차) 기록이 주어졌을 때, 차량별로 주차 요금을 계산하려고 합니다. 아래는 하나의 예시를 나타냅니다.
주차 요금을 나타내는 정수 배열 fees, 자동차의 입/출차 내역을 나타내는 문자열 배열 records가 매개변수로 주어집니다. 차량 번호가 작은 자동차부터 청구할 주차 요금을 차례대로 정수 배열에 담아서 return 하도록 solution 함수를 완성해주세요.
import (
"math"
"sort"
"strings"
"time"
)
const (
Layout = "15:04"
LastTime = "23:59"
)
func solution(fees []int, records []string) []int {
useTimes, vehicles := calculateTimesByVehicles(records)
return calculateFeesByVehicles(fees, useTimes, vehicles)
}
func calculateTimesByVehicles(records []string) (map[string]float64, []string) {
var temp = map[string][]string{}
var result = map[string]float64{}
var tempVehicles = map[string][]string{}
var vehicles []string
for _, record := range records {
recordSlice := strings.Split(record, " ")
tm := recordSlice[0]
num := recordSlice[1]
temp[num] = append(temp[num], tm)
if !isDuplicate(vehicles, num) {
vehicles = append(vehicles, num)
}
}
sort.Strings(vehicles)
for _, vh := range vehicles {
tempVehicles[vh] = temp[vh]
}
for k, vh := range tempVehicles {
if len(vh)%2 == 0 {
continue
}
vh = append(vh, LastTime)
tempVehicles[k] = vh
}
for _, vh := range vehicles {
v := tempVehicles[vh]
for i := len(v) - 1; i >= 0; i-- {
if i%2 == 0 {
continue
}
result[vh] += getDurationTwoTimes(v[i], v[i-1])
}
}
return result, vehicles
}
func isDuplicate(vehicles []string, vehicle string) bool {
for _, vh := range vehicles {
if vh == vehicle {
return true
}
}
return false
}
func getDurationTwoTimes(after, before string) float64 {
a, _ := time.Parse(Layout, after)
b, _ := time.Parse(Layout, before)
return a.Sub(b).Minutes()
}
func calculateFeesByVehicles(fees []int, useTimes map[string]float64, vehicles []string) []int {
baseMinute := float64(fees[0])
baseFee := float64(fees[1])
unitMinute := float64(fees[2])
unitFee := float64(fees[3])
var result []int
for _, vh := range vehicles {
useTime := useTimes[vh]
if useTime <= baseMinute {
result = append(result, int(baseFee))
continue
}
sum := baseFee + math.Ceil((useTime-baseMinute)/unitMinute)*unitFee
result = append(result, int(sum))
}
return result
}
[Programmers] Lv.2 할인 행사 (Go) (0) | 2022.11.13 |
---|---|
[Programmers] Lv.2 2개 이하로 다른 비트 (Go) (0) | 2022.11.13 |
[Programmers] Lv.1 푸드 파이트 대회 (Go) (0) | 2022.11.09 |
[Programmers] Lv.2 연속 부분 수열 합의 개수 (Go) (0) | 2022.11.08 |
[Programmers] Lv.2 다리를 지나는 트럭 (Go) (0) | 2022.11.06 |
댓글 영역