TIL_250324

듀듀·2025년 3월 24일

spring_TIL

목록 보기
26/53

오늘은 날 괴롭혔던 코드카타에 대해 쓰겠다.
30분안에 풀기로 자체 미션 걸었는데 참담하게 실패했다.
해결 방식은 맞았는데 코드를 너무 복잡하게 짜서 코드 안에서 코드 작성자가 길을 잃었다(?).... 그래서 복습!


주차 요금 계산

링크텍스트

문제

입출력 예로 간단하게 설명하자면
IN은 입차 시간이고 OUT은 출차 시간이다.
출차 시간 - 입차 시간을 구해 주차 시간을 구한다
fees[기본 시간, 기본 요금, 단위 시간, 단위 요금]
차량 번호 오름차순으로 주차 요금 구하기!

푼 방법

  1. 입차 시간을 담을 map
  2. 총 주차 시간을 담을 map
  3. 출차일 경우 입차 map에서 시간을 찾아 출차 시간에서 빼준다
  4. 해당 차는 출차 하였으므로 입차 map에서 삭제
  5. 마지막까지 출차하지 않은 차는 출차 시간을 23:59 (1439분)으로 계산
  6. list를 활용하여 차량 번호순으로 오름차순 정렬
  7. 요금 계산
    7-1. 주차 시간이 기본 시간보다 작으면 기본 요금
    7-2. 주차 시간이 기본 시간보다 크면 기본 시간을 제외한 시간에 단위 요금 곱하기!
    7-3. 이때, 예를 들어 154분이면 올림하여 요금 계산!
    -> 154 / 10 -> 16 * 단위 요금으로 계산

틀린 코드

import java.util.*;
class Solution {
    public int[] solution(int[] fees, String[] records) {

        //입차 정보를 담을 map
        HashMap<String, String> in = new HashMap<>();
        
        //차량별 주차 시간을 담을 map
        HashMap<String, Integer> map = new HashMap<>();
        
        for(String str:records) {
            String[] temp = str.split(" ");
            String time = temp[0];
            String car = temp[1];
            String status = temp[2];
            
            //입차인 경우 입차 map에 담기
            if(status.equals("IN")) {
                in.put(car, time);
            }
            //출차인 경우 시간 계산 + 입차 map에서 삭제
            else {
                String[] temp_out = time.split(":");
                int out_time = Integer.parseInt(temp_out[0])*60 + Integer.parseInt(temp_out[1]);
                
                String[] temp_in = in.get(car).split(":");
                int in_time = Integer.parseInt(temp_in[0])*60 + Integer.parseInt(temp_in[1]);
                
                map.put(car, map.getOrDefault(car,0)+(out_time-in_time));
                
                //입차 map에서 삭제
                in.remove(car);
            }
        }
        
        //마지막까지 출차하지 않은 차 계산
        for(String s:in.keySet()) {
            String[] temp_in = in.get(s).split(":");
            int in_time = Integer.parseInt(temp_in[0])*60 + Integer.parseInt(temp_in[1]);
            map.put(s, map.getOrDefault(s,0)+(1439-in_time));
        }
        
        //오름차순 정렬
        ArrayList<String> list = new ArrayList<>(map.keySet());
        Collections.sort(list);
        
        int[] answer = new int[list.size()];
        int idx = 0;
        //요금 계산
        for(String s:list) {
            //기본시간 보다 작다면
            if(map.get(s) <= fees[0]) {
                answer[idx] = fees[1];
            }
            else {
                answer[idx] = (Math.ceil((double)((map.get(s) - fees[0]) / fees[2])) * fees[3]) + fees[1];
            }
            idx++;
        }
        
        return answer;
    }
}

도대체 어디서 실수한지 모르겠어서 GPT 호출


정답 코드

import java.util.*;
class Solution {
    public int[] solution(int[] fees, String[] records) {

        //입차 정보를 담을 map
        HashMap<String, String> in = new HashMap<>();
        
        //차량별 주차 시간을 담을 map
        HashMap<String, Integer> map = new HashMap<>();
        
        for(String str:records) {
            String[] temp = str.split(" ");
            String time = temp[0];
            String car = temp[1];
            String status = temp[2];
            
            //입차인 경우 입차 map에 담기
            if(status.equals("IN")) {
                in.put(car, time);
            }
            //출차인 경우 시간 계산 + 입차 map에서 삭제
            else {
                String[] temp_out = time.split(":");
                int out_time = Integer.parseInt(temp_out[0])*60 + Integer.parseInt(temp_out[1]);
                
                String[] temp_in = in.get(car).split(":");
                int in_time = Integer.parseInt(temp_in[0])*60 + Integer.parseInt(temp_in[1]);
                
                map.put(car, map.getOrDefault(car,0)+(out_time-in_time));
                
                //입차 map에서 삭제
                in.remove(car);
            }
        }
        
        //마지막까지 출차하지 않은 차 계산
        for(String s:in.keySet()) {
            String[] temp_in = in.get(s).split(":");
            int in_time = Integer.parseInt(temp_in[0])*60 + Integer.parseInt(temp_in[1]);
            map.put(s, map.getOrDefault(s,0)+(1439-in_time));
        }
        
        //오름차순 정렬
        ArrayList<String> list = new ArrayList<>(map.keySet());
        Collections.sort(list);
        
        int[] answer = new int[list.size()];
        int idx = 0;
        //요금 계산
        for(String s:list) {
            //기본시간 보다 작다면
            if(map.get(s) <= fees[0]) {
                answer[idx] = fees[1];
            }
            else {
                answer[idx] = (int)((Math.ceil((double)(map.get(s) - fees[0]) / fees[2])) * fees[3]) + fees[1];
            }
            idx++;
        }
        
        return answer;
    }
}

뭐가 다르냐고요? 그니깐요;;;

틀린 코드

 answer[idx] = (Math.ceil((double)((map.get(s) - fees[0]) / fees[2])) * fees[3]) + fees[1];

ㅇㅋ
double형을 int형과 계산할 수 없다 ㅇㅋㅇㅋ

그래서 수정했다

answer[idx] = (int)(Math.ceil((double)((map.get(s) - fees[0]) / fees[2])) * fees[3]) + fees[1];

수정했는데 틀렸음
(double) 변환 → 이미 정수 나눗셈이 적용된 후라 변환 의미 없음

정답 코드

answer[idx] = (int)((Math.ceil((double)(map.get(s) - fees[0]) / fees[2])) * fees[3]) + fees[1];

오늘의 교훈: 괄호를 잘 치자
어려운 문제는 풀고 나면 쾌감이 든다

0개의 댓글