C# 프로그래머스 주차 요금 계산

장현태입니다·2026년 3월 18일

  1. TimeCheck : string to int 형식의 시간계산 메서드
  2. FeeCount : 시간에 따른 정산
  3. FeeCount 메서드에서 해당 Math.Celling을 통해 값이 0 이되는 현상 제거
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
    public int[] solution(int[] fees, string[] records)
    {

        // records 데이터 정리
        string[,] str = new string[records.Length, 3];

        for (int i = 0; i < records.Length; i++)
        {
            string[] data = records[i].Split(" ");

            str[i, 0] = data[0];
            str[i, 1] = data[1];
            str[i, 2] = data[2];
        }


        // 차량번호 : 존재시간
        Dictionary<int, int> dic = new Dictionary<int, int>();

        // 차량 번호 : start 시간
        Dictionary<int, string> existDic = new Dictionary<int, string>();

        for (int i = 0; i < str.GetLength(0); i++)
        {
            int count = 0;
            var carNum = int.Parse(str[i, 1]);

            if (existDic.ContainsKey(carNum))
            {
                if (str[i, 2] == "IN")
                    continue;

                count = TimeCheck(existDic[carNum], str[i, 0]);
                existDic.Remove(carNum);
            }
            else
            {
                if (str[i, 2] == "OUT")
                    continue;

                existDic.Add(carNum, str[i, 0]);
            }

            if (dic.ContainsKey(carNum))
            {
                dic[carNum] += count;
            }
            else
            {
                dic.Add(carNum, count);
            }

        }

        foreach (KeyValuePair<int, string> data in existDic)
        {
            var count = TimeCheck(data.Value, "23:59");

            if (dic.ContainsKey(data.Key))
            {
                dic[data.Key] += count;
            }
            else
            {
                dic.Add(data.Key, count);
            }
        }

        var sorted = dic.OrderBy(x => x.Key);
        List<int> list = new List<int>();

        foreach (var data in sorted)
        {
            list.Add(FeeCount(fees, data.Value));
        }

        return list.ToArray();
    }

    public int TimeCheck(string start, string end)
    {
        string[] strS = start.Split(":");
        string[] strE = end.Split(":");

        int count = 0;
        count = ((int.Parse(strE[0]) * 60 + int.Parse(strE[1]))) -
            ((int.Parse(strS[0]) * 60 + int.Parse(strS[1])));

        return count;
    }

    public int FeeCount(int[] fees, int time)
    {
        if (time <= fees[0])
            return fees[1];

        int extraTime = time - fees[0];

        int unit = (int)Math.Ceiling((double)extraTime / fees[2]);

        int fee = fees[1] + unit * fees[3];

        return fee;
    }


}

0개의 댓글