CodingTest/Programmers Lv.2
[프로그래머스 C#] Lv.2 주차 요금 계산
주녘
2024. 2. 8. 19:40
https://school.programmers.co.kr/learn/courses/30/lessons/92341
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
1. 정답코드 및 핵심 아이디어, 유의사항
입차시간과 출차시간에 따라 누적 주차시간을 구하고, 누적 주차시간에 따른 비용을 구하는 문제
- 문제에서의 주차장은 입차횟수에 관계없이 하루 누적 주차시간에 따른 비용을 청구함
- 만약, 입차만 하고 출차를 하지 않았을 경우에 23:59에 출차했다고 가정
- 차량번호를 기준으로 오름차순 정렬하여 비용을 배열에 담아 반환해야 함
누적 시간 구하기
- 입차한 차에 대한 entryDict, 누적 주차시간에 대한 timeDict을 따로 선언
- 출차한 경우 누적시간을 구해 timeDict에 추가 및 entryDict에서 삭제
- 마지막까지 남아있는 차량에 대해서 따로 처리 (entryDict 안에 값이 남아있다면)
주석 참조
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution
{
public int[] solution(int[] fees, string[] records)
{
var answerList = new List<int>();
var entryDict = new Dictionary<int, int>(); // <차량번호, 입차시간>
var timeDict = new Dictionary<int, int>(); // <차량번호, 누적시간>
foreach (string str in records)
{
string[] strs = str.Split(" "); // [시간, 차량번호, 입차출차]
string[] times = strs[0].Split(":"); // [시, 분]
int time = int.Parse(times[0]) * 60 + int.Parse(times[1]); // 시간(분)
int carNum = int.Parse(strs[1]); // 차량번호
if (strs[2] == "IN")
{
// 입차한 경우
entryDict.Add(carNum, time);
}
else // strs[2] == "OUT"
{
// 출차한 경우
int currTime = time - entryDict[carNum]; // 이용시간
if (timeDict.ContainsKey(carNum))
timeDict[carNum] += currTime;
else
timeDict.Add(carNum, currTime);
entryDict.Remove(carNum);
}
}
// 입차만 하고 출차하지 않은 차량 처리
if (entryDict.Count > 0)
{
var tempList = entryDict.Keys.ToList(); // 출차하지 않은 차량번호 리스트
foreach (int carNum in tempList)
{
// 23:59 출차로 처리
int currTime = 23 * 60 + 59 - entryDict[carNum]; // 이용시간
if (timeDict.ContainsKey(carNum))
timeDict[carNum] += currTime;
else
timeDict.Add(carNum, currTime);
}
}
// 차량번호를 기준으로 오름차순 정렬
var list = timeDict.Keys.ToList();
list.Sort();
// 비용 측정
foreach (int carNum in list)
{
int cost = fees[1]; // 기본 요금
int time = timeDict[carNum] - fees[0]; // 기본 시간
if (time > 0)
{
int num = (int)Math.Ceiling((double)time / fees[2]); // 단위 요금에 대한 개수
cost += num * fees[3]; // 단위 요금 개수 * 단위 요금
}
answerList.Add(cost);
}
return answerList.ToArray();
}
}