코테/프로그래머스

[프로그래머스/Lv. 2] 주차 요금 계산 (JAVA)

imname1am 2023. 11. 21. 17:32
반응형

🔺 문제

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

 

🔺 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.*;
 
class Solution {
    public int[] solution(int[] fees, String[] records) {
        
        Map<StringString> map = new HashMap<>();      // 차 번호, 시간
        Map<String, Integer> feeMap = new TreeMap<>();  // 차 번호, 누적 요금 (TreeMap : 차량번호 기준 오름차순 정렬)
        
        for(int i = 0 ; i < records.length ; i++) {
            feeMap.put(records[i].split(" ")[1], 0);
        }
        
        // IN-OUT 기록 둘 다 있는 경우
        for(int i = 0 ; i < records.length ; i++) {
            String[] infos = records[i].split(" ");
            
            if(map.containsKey(infos[1])) {    // IN 기록이 있다면
                String[] inTime = map.remove(infos[1]).split(":");
                String[] outTime = infos[0].split(":");
                
                int HH = Integer.parseInt(outTime[0]) - Integer.parseInt(inTime[0]);
                int MM = Integer.parseInt(outTime[1]) - Integer.parseInt(inTime[1]);
                
                feeMap.replace(infos[1], feeMap.get(infos[1]) + 60 * HH + MM);
            }
            else {
                map.put(infos[1], infos[0]);    // 차 번호, 시간
            }
        }
        
        // IN 기록만 있는 경우
        for(String key : map.keySet()) {
            String[] inTime = map.get(key).split(":");
            
            int HH = 23 - Integer.parseInt(inTime[0]);
            int MM = 59 - Integer.parseInt(inTime[1]);
            
            feeMap.replace(key, feeMap.get(key) + 60 * HH + MM);
        }
        
        List<Map.Entry<String,Integer>> list = new ArrayList(feeMap.entrySet());    // 차량번호 기준 오름차순 정렬된 리스트
        
        int[] answer = new int[list.size()];
        for(int i = 0 ; i < answer.length ; i++) {
            if(list.get(i).getValue() > fees[0]) {
                answer[i] = fees[1+ (int)Math.ceil((list.get(i).getValue() - fees[0]) / (double)fees[2]) * fees[3];
            }
            else {
                answer[i] = fees[1];
            }
        }
        
        return answer;
    }
}
cs

 

 

 

🧩  해결 아이디어

• Map

- 첫 번째 Map : 차량 번호와 시간 저장하는 HashMap

- 두 번째 Map : 차량 번호와 누적 요금 저장하는 TreeMap (그러면 차량 번호 기준 오름차순 정렬 가능하므로)

 

- 입차, 출차 기록이 모두 있다면, 소요 시간(= 출차 시간 - 입차 시간)만큼 요금을 부과해 두 번째 TreeMap에 누적 요금을 저장한다.

- 입차 기록만 있다면, 23시 59분에서 입차 시간을 뺀만큼 요금을 부과해 누적 요금을 저장한다.

feeMap.get(infos[1]) + 60 * HH + MM

 

 

- 기본시간 초과 시, 추가 요금 계산은 이렇게 (꼭 double을 추가해줘야 나눗셈 계산을 제대로 할 수 있다.)

if(list.get(i).getValue() > fees[0]) {
    answer[i] = fees[1] + (int)Math.ceil((list.get(i).getValue() - fees[0]) / (double)fees[2]) * fees[3];
}

 

 

 

 


🔺 다른 풀이들

- 이게 복습용으로 좋은 듯..

 

[Java/자바] 프로그래머스 Lv2 - 주차 요금 계산 (HashMap, TreeMap)

문제 설명 주차장의 요금표와 차량이 들어오고(입차) 나간(출차) 기록이 주어졌을 때, 차량별로 주차 요금을 계산하려고 합니다. 아래는 하나의 예시를 나타냅니다. 요금표 기본 시간(분) 기본

hstory0208.tistory.com

 


💬 느낀 점

Map 쓸 생각은 했는데..

그 이후로 머리가 잘 구르지 않음..

머리야 잘 굴러줘 제발...ㅠ

 

1회독 2회독 3회독 4회독 5회독
V 240217      

 

 

(+240217 2회독)

70분 소요..

 

코드 확인하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import java.util.*;
 
class Solution {
    public int[] solution(int[] fees, String[] records) {
        int basicTime = fees[0];
        int basicFee = fees[1];
        int perTime = fees[2];
        int perFee = fees[3];
            
        Map<StringString> map = new HashMap<>();      // 차량 번호, 시각
        Map<String, Integer> map2 = new HashMap<>();    // 차량 번호, 누적 주차 시간
        
        for(int i = 0 ; i < records.length ; i++) {
            String[] info = records[i].split(" ");
            
            String time = info[0];            
            String carNum = info[1];
            String cmd = info[2];
            
            if(cmd.equals("IN")) {
                if(!map.containsKey(carNum) && !info[0].equals("23:59"))
                    map.put(carNum, time);
            }
            else {
                if(map.containsKey(carNum)) {
                    String[] startInfo = map.get(carNum).split(":");
                    int startH = Integer.parseInt(startInfo[0]);
                    int startM = Integer.parseInt(startInfo[1]);
                    
                    String[] endInfo = time.split(":");
                    int endH = Integer.parseInt(endInfo[0]);
                    int endM = Integer.parseInt(endInfo[1]);
                    
                    // 누적 주차 시간 세기
                    int tmpTime = 0;
                    
                    int HH = endH - startH;
                    int MM = 0;
                    
                    if(endM < startM) {
                        MM = (endM + 60- startM;
                        HH--;
                    }
                    else {
                        MM = endM - startM;
                    }
                    
                    tmpTime = 60 * HH + MM;                    
                    map2.put(carNum, map2.getOrDefault(carNum, 0+ tmpTime);   // 누적 주차 시간 저장
                    
                    map.remove(carNum); // 키 삭제
                }
            }
        }
        
        // 남은 주차 중인 차들 처리
        for(String carNum : map.keySet()) {
            String[] time = map.get(carNum).split(":");
 
            int tmpTime = (23 - Integer.parseInt(time[0])) * 60 + (59 - Integer.parseInt(time[1]));
 
            map2.put(carNum, map2.getOrDefault(carNum, 0+ tmpTime);
        }
        
        // 주차 요금 계산하기
        List<Node> list = new ArrayList<>();
        
        for(String carNum : map2.keySet()) {
            int time = map2.get(carNum);
            int fee = basicFee;
            
            if(time > basicTime) {
                fee += (int)Math.ceil((time - basicTime) / (double)perTime) * perFee;   // 정확한 나눗셈 연산 위해 double을 꼭 해줘야 함!
            }
            list.add(new Node(carNum, time, fee));
        }     
        
        Collections.sort(list); // 차량 번호가 작은 자동차부터 되도록 리스트 정렬
        
        int[] answer = new int[list.size()];    // 차별 주차 요금
        for(int i = 0 ; i < answer.length ; i++) {
            answer[i] = list.get(i).money;
        }
        return answer;
    }
}
 
class Node implements Comparable<Node> {
    String num;
    int time, money;
    
    public Node(String num, int time, int money) {
        this.num = num;
        this.time = time;
        this.money = money;
    }
    
    // 차량 번호 오름차순 정렬
    @Override
    public int compareTo(Node n) {
        return Integer.parseInt(this.num) - Integer.parseInt(n.num);
    }
}
cs


(참고)

 

[프로그래머스] 주차 요금 계산(Java 자바)

https://programmers.co.kr/learn/courses/30/lessons/92341 코딩테스트 연습 - 주차 요금 계산 [180, 5000, 10, 600] ["05:34 5961 IN", "06:00 0000 IN", "06:34 0000 OUT", "07:59 5961 OUT", "07:59 0148 IN", "18:59 0000 IN", "19:09 0148 OUT", "22:59 59

tmdrl5779.tistory.com

 

반응형