본문 바로가기

Java/Java 알고리즘 프로그래머스

[스킬체크 - LEVEL.2] 주차 요금 계산

반응형
  • 주차 요금 계산
문제 설명
문제 설명

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

  • 요금표
기본 시간(분)기본 요금(원)단위 시간(분)단위 요금(원)
180 5000 10 600

 

  • 입/출차 기록
시각(시:분)차량 번호내역
05:34 5961 입차
06:00 0000 입차
06:34 0000 출차
07:59 5961 출차
07:59 0148 입차
18:59 0000 입차
19:09 0148 출차
22:59 5961 입차
23:00 5961 출차

 

  • 자동차별 주차 요금
차량 번호누적 주차 시간(분)주차 요금(원)
0000 34 + 300 = 334 5000 + ⌈(334 - 180) / 10⌉ x 600 = 14600
0148 670 5000 +⌈(670 - 180) / 10⌉x 600 = 34400
5961 145 + 1 = 146 5000
  • 어떤 차량이 입차된 후에 출차된 내역이 없다면, 23:59에 출차된 것으로 간주합니다.
    • 0000번 차량은 18:59에 입차된 이후, 출차된 내역이 없습니다. 따라서, 23:59에 출차된 것으로 간주합니다.
  • 00:00부터 23:59까지의 입/출차 내역을 바탕으로 차량별 누적 주차 시간을 계산하여 요금을 일괄로 정산합니다.
  • 누적 주차 시간이 기본 시간이하라면, 기본 요금을 청구합니다.
  • 누적 주차 시간이 기본 시간을 초과하면, 기본 요금에 더해서, 초과한 시간에 대해서 단위 시간 마다 단위 요금을 청구합니다.
    • 초과한 시간이 단위 시간으로 나누어 떨어지지 않으면, 올림합니다.
    • ⌈a⌉ : a보다 작지 않은 최소의 정수를 의미합니다. 즉, 올림을 의미합니다.

주차 요금을 나타내는 정수 배열 fees, 자동차의 입/출차 내역을 나타내는 문자열 배열 records가 매개변수로 주어집니다. 차량 번호가 작은 자동차부터 청구할 주차 요금을 차례대로 정수 배열에 담아서 return 하도록 solution 함수를 완성해주세요.

제한사항
  • fees의 길이 = 4
    • fees[0] = 기본 시간(분)
    • 1 ≤ fees[0] ≤ 1,439
    • fees[1] = 기본 요금(원)
    • 0 ≤ fees[1] ≤ 100,000
    • fees[2] = 단위 시간(분)
    • 1 ≤ fees[2] ≤ 1,439
    • fees[3] = 단위 요금(원)
    • 1 ≤ fees[3] ≤ 10,000
  • 1 ≤ records의 길이 ≤ 1,000
    • records의 각 원소는 "시각 차량번호 내역" 형식의 문자열입니다.
    • 시각, 차량번호, 내역은 하나의 공백으로 구분되어 있습니다.
    • 시각은 차량이 입차되거나 출차된 시각을 나타내며, HH:MM 형식의 길이 5인 문자열입니다.
      • HH:MM은 00:00부터 23:59까지 주어집니다.
      • 잘못된 시각("25:22", "09:65" 등)은 입력으로 주어지지 않습니다.
    • 차량번호는 자동차를 구분하기 위한, `0'~'9'로 구성된 길이 4인 문자열입니다.
    • 내역은 길이 2 또는 3인 문자열로, IN 또는 OUT입니다. IN은 입차를, OUT은 출차를 의미합니다.
    • records의 원소들은 시각을 기준으로 오름차순으로 정렬되어 주어집니다.
    • records는 하루 동안의 입/출차된 기록만 담고 있으며, 입차된 차량이 다음날 출차되는 경우는 입력으로 주어지지 않습니다.
    • 같은 시각에, 같은 차량번호의 내역이 2번 이상 나타내지 않습니다.
    • 마지막 시각(23:59)에 입차되는 경우는 입력으로 주어지지 않습니다.
    • 아래의 예를 포함하여, 잘못된 입력은 주어지지 않습니다.
      • 주차장에 없는 차량이 출차되는 경우
      • 주차장에 이미 있는 차량(차량번호가 같은 차량)이 다시 입차되는 경우

입출력 예feesrecordsresult
[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 5961 IN", "23:00 5961 OUT"] [14600, 34400, 5000]
[120, 0, 60, 591] ["16:00 3961 IN","16:00 0202 IN","18:00 3961 OUT","18:00 0202 OUT","23:58 3961 IN"] [0, 591]
[1, 461, 1, 10] ["00:00 1234 IN"] [14841]

입출력 예 설명

입출력 예 #1

문제 예시와 같습니다.

입출력 예 #2

  • 요금표
기본 시간(분)기본 요금(원)단위 시간(분)단위 요금(원)
120 0 60 591

 

  • 입/출차 기록
시각(시:분)차량 번호내역
16:00 3961 입차
16:00 0202 입차
18:00 3961 출차
18:00 0202 출차
23:58 3961 입차

 

  • 자동차별 주차 요금
차량 번호누적 주차 시간(분)주차 요금(원)
0202 120 0
3961 120 + 1 = 121 0 +⌈(121 - 120) / 60⌉x 591 = 591
  • 3961번 차량은 2번째 입차된 후에는 출차된 내역이 없으므로, 23:59에 출차되었다고 간주합니다.

 

입출력 예 #3

  • 요금표
기본 시간(분)기본 요금(원)단위 시간(분)단위 요금(원)
1 461 1 10

 

  • 입/출차 기록
시각(시:분)차량 번호내역
00:00 1234 입차

 

  • 자동차별 주차 요금
차량 번호누적 주차 시간(분)주차 요금(원)
1234 1439 461 +⌈(1439 - 1) / 1⌉x 10 = 14841
  • 1234번 차량은 출차 내역이 없으므로, 23:59에 출차되었다고 간주합니다.

제한시간 안내
  • 정확성 테스트 : 10초

import java.time.*;
import java.time.temporal.*;
import java.util.*;
class Car{
    String id;
    boolean flag;
    LocalTime in, out;
    Car(String id, boolean flag, LocalTime in, LocalTime out){
        this.id=id;
        this.flag=flag;
        this.in=in;
        this.out=out;
    }
        @Override
    public boolean equals(Object object) {
        Car car = (Car) object;
        // 다른건 상관없이, id만 같으면 true를 리턴합니다.
        
        if (car.id.equals(this.id)) {
            return true;
        }
        return false;
    }

}
class Solution {
    public Integer[] solution(int[] fees, String[] records) {
        ArrayList<Car> list = new ArrayList<>();
        
        //차량 번호가 작은 자동차 순서대로 [오름차순]-> TreeMap
        Map<String, Integer> map = new TreeMap<>();
        
        //입차 차량
        for(int i=0;i<records.length;i++){
            String[] tmp = records[i].split(" ");
            if(tmp[2].equals("IN")){
    if(list.contains(new Car(tmp[1], false,LocalTime.parse("11:11"),LocalTime.parse("11:11")))){
        
        int tmp2 =list.indexOf(new Car(tmp[1], false,LocalTime.parse("11:11"),LocalTime.parse("11:11")));
        Car car =list.get(tmp2);
        list.set(tmp2, new Car(car.id, false, LocalTime.parse(tmp[0]), car.out));
                    System.out.println("두번째 입차 "+car.id+" "+car.in);
                }
                else{
list.add(new Car(tmp[1], false,LocalTime.parse(tmp[0]),LocalTime.parse("23:59")));
                    System.out.println("첫번째 입차 "+tmp[1]+" "+LocalTime.parse(tmp[0]));
                }
                    
            }
            
            //출차 차량
            if(tmp[2].equals("OUT")){
    if(list.contains(new Car(tmp[1], true,LocalTime.parse("11:11"),LocalTime.parse("11:11")))){
        
        int tmp2 =list.indexOf(new Car(tmp[1], true,LocalTime.parse("11:11"),LocalTime.parse("11:11")));
        Car car =list.get(tmp2);
        list.set(tmp2, new Car(car.id, true, car.in, LocalTime.parse(tmp[0])));
                    System.out.println("출차 "+car.id+" "+LocalTime.parse(tmp[0]));
        car =list.get(tmp2);

                 long minutes = ChronoUnit.MINUTES.between(car.in, car.out);
        map.put(car.id, map.getOrDefault(car.id, 0)+(int)minutes);
                     System.out.println("누적주차시간"+map.get(car.id));
    }
                    
            }
        }
        
        //출차하지 않은 차량 확인
        for(Car y : list){
            if(!y.flag) {
                int tmp2 =list.indexOf(new Car(y.id, true,LocalTime.parse("11:11"),LocalTime.parse("11:11")));
                 Car car =list.get(tmp2);
                 long minutes = ChronoUnit.MINUTES.between(car.in, LocalTime.parse("23:59"));
                System.out.println();
                map.put(y.id, map.getOrDefault(y.id, 0)+(int)minutes);
                System.out.println("출차 X"+y.id+" "+map.get(y.id));
            }
        }
        
        //총 주차 시간을 이용해 주차 요금 계산
        for(String x : map.keySet()){
            int y = map.get(x);
            if(y>fees[0]){
                System.out.println("총 주차 시간"+y);
                System.out.println((int)Math.ceil((float)(y-fees[0])/fees[2]));
                map.put(x, fees[1]+((int)Math.ceil((float)(y-fees[0])/fees[2])*fees[3]));
            }
            else{
                System.out.println("총 주차 시간"+y);
                map.put(x, fees[1]);
            }
        }

        Collection<Integer> values = map.values();        
        Integer [] answer = values.toArray(new Integer[0]);
        return answer;
    }
}

 

 

 

+) 다른 사람의 풀이1

import java.util.*;

class Solution {

    public int timeToInt(String time) {
        String temp[] = time.split(":");
        return Integer.parseInt(temp[0])*60 + Integer.parseInt(temp[1]);
    }
    public int[] solution(int[] fees, String[] records) {

        TreeMap<String, Integer> map = new TreeMap<>();

        for(String record : records) {
            String temp[] = record.split(" ");
            int time = temp[2].equals("IN") ? -1 : 1;
            time *= timeToInt(temp[0]);
            map.put(temp[1], map.getOrDefault(temp[1], 0) + time);
        }
        int idx = 0, ans[] = new int[map.size()];
        for(int time : map.values()) {
            if(time < 1) time += 1439;
            time -= fees[0];
            int cost = fees[1];
            if(time > 0)
                cost += (time%fees[2] == 0 ? time/fees[2] : time/fees[2]+1)*fees[3];

            ans[idx++] = cost;
        }
        return ans;
    }
}

 

+) 다른 사람의 풀이2

import java.time.LocalTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

class Solution {
    public int[] solution(int[] fees, String[] records) {
        FeeTable feeTable = new FeeTable(fees[0], fees[1], fees[2], fees[3]);

        Records record = Arrays.stream(records)
                .map(Record::parse)
                .collect(Collectors.collectingAndThen(
                        Collectors.groupingBy(Record::getCar), Records::new));

        return record.calculateFees(feeTable).stream()
                .mapToInt(i -> i)
                .toArray();
    }

    private static class Car implements Comparable<Car> {
        private final String number;

        public Car(String number) {
            this.number = number;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Car car = (Car) o;
            return Objects.equals(number, car.number);
        }

        @Override
        public int hashCode() {
            return Objects.hash(number);
        }

        @Override
        public int compareTo(Car other) {
            return this.number.compareTo(other.number);
        }
    }

    private static class Records {
        private static final LocalTime DEFAULT_OUT_TIME = LocalTime.parse("23:59");
        private final Map<Car, List<Record>> records;

        public Records(Map<Car, List<Record>> records) {
            this.records = records;
        }

        public List<Integer> calculateFees(FeeTable feeTable) {
            return records.entrySet().stream()
                    .sorted(Map.Entry.comparingByKey())
                    .map(Map.Entry::getValue)
                    .map(record -> calculateFee(record, feeTable))
                    .collect(Collectors.toList());
        }

        private Integer calculateFee(List<Record> record, FeeTable feeTable) {
            Collections.sort(record);

            int index = 0;
            int differ = 0;

            while (index < record.size()) {
                differ += calculateDiffer(record, index);
                index += 2;
            }

            if (differ <= feeTable.getBaseTimeMinutes()) {
                return feeTable.getBaseFee();
            }

            int withoutBase = differ - feeTable.getBaseTimeMinutes();
            int remainder = withoutBase % feeTable.getUnitTimeMinutes() > 0 ? 1 : 0;

            return feeTable.getBaseFee() + (remainder + withoutBase / feeTable.getUnitTimeMinutes()) * feeTable.unitFee;
        }

        private Integer calculateDiffer(List<Record> record, int index) {
            Record in = record.get(index);
            Record out = getNextRecord(record, in.getCar(), index);

            return in.getDifferFrom(out);
        }

        private Record getNextRecord(List<Record> record, Car car, int index) {
            if (index + 1 >= record.size()) {
                return new Record(RecordType.OUT, car, DEFAULT_OUT_TIME);
            }

            return record.get(index + 1);
        }
    }

    private static class Record implements Comparable<Record> {
        private final RecordType type;
        private final Car car;
        private final LocalTime time;

        public Record(RecordType type, Car car, LocalTime time) {
            this.type = type;
            this.car = car;
            this.time = time;
        }

        public static Record parse(String rawRecord) {
            String[] record = rawRecord.split(" ");
            LocalTime time = LocalTime.parse(record[0]);
            Car car = new Car(record[1]);
            RecordType recordType = RecordType.findType(record[2]);

            return new Record(recordType, car, time);
        }

        public Car getCar() {
            return car;
        }

        public boolean isOut() {
            return type.isOut();
        }

        public boolean isInBaseTime(Record other, int baseTime) {
            return getDifferFrom(other) <= baseTime;
        }

        public Integer getDifferFrom(Record other) {
            int here = TimeUtils.toMinutes(time);
            int otherTime = TimeUtils.toMinutes(other.time);
            return Integer.max(here, otherTime) - Integer.min(here, otherTime);
        }

        @Override
        public int compareTo(Record o) {
            return this.time.compareTo(o.time);
        }
    }

    private static class TimeUtils {
        public static Integer toMinutes(LocalTime time) {
            return time.getHour() * 60 + time.getMinute();
        }
    }

    private enum RecordType {
        IN,
        OUT;

        public static RecordType findType(String type) {
            return Arrays.stream(values())
                    .filter(t -> t.name().equals(type))
                    .findAny()
                    .orElseThrow(IllegalArgumentException::new);
        }

        public boolean isIn() {
            return IN.equals(this);
        }

        public boolean isOut() {
            return OUT.equals(this);
        }
    }

    private static class FeeTable {
        private final Integer baseTimeMinutes;
        private final Integer baseFee;
        private final Integer unitTimeMinutes;
        private final Integer unitFee;

        public FeeTable(Integer baseTimeMinutes, Integer baseFee,
                        Integer unitTimeMinutes, Integer unitFee) {
            this.baseTimeMinutes = baseTimeMinutes;
            this.baseFee = baseFee;
            this.unitTimeMinutes = unitTimeMinutes;
            this.unitFee = unitFee;
        }

        public Integer getBaseTimeMinutes() {
            return baseTimeMinutes;
        }

        public Integer getBaseFee() {
            return baseFee;
        }

        public Integer getUnitTimeMinutes() {
            return unitTimeMinutes;
        }

        public Integer getUnitFee() {
            return unitFee;
        }
    }
}

# 날짜와 시간을 처리하는 라이브러리 가져오기

import java.time.*;
import java.time.temporal.*;
import java.util.*;

 

# LocalTime라이브러리를 이용해 날짜와 시간 처리

//시간 추가
int tmp2 =list.indexOf(new Car(tmp[1], true,LocalTime.parse("11:11"),LocalTime.parse("11:11")));

//누적 주차 시간 구하기
long minutes = ChronoUnit.MINUTES.between(car.in, LocalTime.parse("23:59"));

 

# List에 객체를 넣었을 때, 객체에 대해서 equals를 오버라이딩 처리

-> Car라는 객체의 id가 같으면 같은 객체 처리

    @Override
public boolean equals(Object object) {
    Car car = (Car) object;
    // 다른건 상관없이, id만 같으면 true를 리턴합니다.

    if (car.id.equals(this.id)) {
        return true;
    }
    return false;
}
    
    
if(tmp[2].equals("IN")){
if(list.contains(new Car(tmp[1], false,LocalTime.parse("11:11"),LocalTime.parse("11:11")))){
    int tmp2 =list.indexOf(new Car(tmp[1], false,LocalTime.parse("11:11"),LocalTime.parse("11:11")));
    Car car =list.get(tmp2);
    
    list.set(tmp2, new Car(car.id, false, LocalTime.parse(tmp[0]), car.out));
    System.out.println("두번째 입차 "+car.id+" "+car.in);
}

 

#출차 차량에 대해서 누적 주차 시간을 이용해 주차 요금을 구하는 함수

//출차 차량
if(tmp[2].equals("OUT")){
if(list.contains(new Car(tmp[1], true,LocalTime.parse("11:11"),LocalTime.parse("11:11")))){

        int tmp2 =list.indexOf(new Car(tmp[1], true,LocalTime.parse("11:11"),LocalTime.parse("11:11")));
        Car car =list.get(tmp2);
        list.set(tmp2, new Car(car.id, true, car.in, LocalTime.parse(tmp[0])));
                System.out.println("출차 "+car.id+" "+LocalTime.parse(tmp[0]));
        car =list.get(tmp2);

             long minutes = ChronoUnit.MINUTES.between(car.in, car.out);
        map.put(car.id, map.getOrDefault(car.id, 0)+(int)minutes);
         System.out.println("누적주차시간"+map.get(car.id));
    }

 

#만약 출차를 하지 않은 차량이 있으면, 출차 시간을 23:59로 지정해주는 함수

//출차하지 않은 차량 확인
for(Car y : list){
    if(!y.flag) {
        int tmp2 =list.indexOf(new Car(y.id, true,LocalTime.parse("11:11"),LocalTime.parse("11:11")));
         Car car =list.get(tmp2);
         long minutes = ChronoUnit.MINUTES.between(car.in, LocalTime.parse("23:59"));
        System.out.println();
        map.put(y.id, map.getOrDefault(y.id, 0)+(int)minutes);
        System.out.println("출차 X"+y.id+" "+map.get(y.id));
    }
}

 

#날짜와 시간을 이용해 주차 요금을 구하는 함수

//총 주차 시간을 이용해 주차 요금 계산
for(String x : map.keySet()){
    int y = map.get(x);
    if(y>fees[0]){
        System.out.println("총 주차 시간"+y);
        System.out.println((int)Math.ceil((float)(y-fees[0])/fees[2]));
        map.put(x, fees[1]+((int)Math.ceil((float)(y-fees[0])/fees[2])*fees[3]));
    }
    else{
        System.out.println("총 주차 시간"+y);
        map.put(x, fees[1]);
    }
}

 

# Map의 값이 Integer일 경우, 배열로 만들기

Collection<Integer> values = map.values();        
Integer [] answer = values.toArray(new Integer[0]);

 

 

-> 기능별 함수화 시키기

 

 

반응형