프로그래머스 - 주차 요금 계산
문제풀이
import java.time.Duration;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Solution {
public int[] solution(int[] fees, String[] records) {
List<Integer> resultList = new ArrayList<>();
Map<Integer, Integer> minutes = new HashMap<>();
for (int i = 0; i < records.length; i++) {
String record = records[i];
String[] info = record.split(" ");
if (info[2].equals("OUT")) {
continue;
}
Integer num = Integer.parseInt(info[1]);
String inTime = info[0];
String outTime = findOutTime(records, num, i);
long diff = betweenMinByStr(inTime, outTime);
Integer timeDiff = minutes.getOrDefault(num, 0) + (int)diff;
minutes.put(num, timeDiff);
}
List<Integer> keyInt = minutes.keySet().stream()
.sorted()
.collect(Collectors.toList());
for (Integer key : keyInt) {
Integer getTime = minutes.get(key);
Integer price = calPrice(getTime, fees);
resultList.add(price);
}
return resultList.stream()
.mapToInt(Integer::intValue)
.toArray();
}
private Integer calPrice(Integer getTime, int[] fees) {
Integer baseDiff = getTime - fees[0] < 0 ? 0 : getTime - fees[0];
int result = fees[1] + ((baseDiff / fees[2]) + (baseDiff % fees[2] > 0? 1 : 0)) * fees[3];
return result;
}
private String findOutTime(String[] records, Integer num, int inIndex) {
String result = null;
for (int j = inIndex + 1; j < records.length; j++) {
String target = records[j];
String[] targetInfo = target.split(" ");
if (num.equals((Integer.parseInt(targetInfo[1])))) {
result = targetInfo[0];
break;
}
}
if (result == null) {
result = "23:59";
}
return result;
}
private long betweenMinByStr(String inTime, String outTime) {
LocalTime time1 = LocalTime.parse(inTime);
LocalTime time2 = LocalTime.parse(outTime);
Duration duration = Duration.between(time1, time2);
return duration.toMinutes();
}
}
- 기록을 순회하며 In인 기록에 대해, Out 기록을 찾아 누적 시간을 계산하는 Map을 생성한다.
- Map을 차량번호 순으로 Key를 정렬하고 하나씩 요금을 계산하여 반환한다.
LocalTime
- java.time 패키지에서 제공하는 클래스로 시간 정보를 표현하는 클래스
- 날짜나 시간대 정보는 포함하지 않고 시간 정보만 나타냄
import java.time.LocalTime;
public class LocalTimeExample {
public static void main(String[] args) {
LocalTime now = LocalTime.now();
System.out.println("현재 시간: " + now);
LocalTime specificTime = LocalTime.of(12, 30, 0);
System.out.println("지정된 시간: " + specificTime);
String timeStr = "15:45";
LocalTime parsedTime = LocalTime.parse(timeStr);
System.out.println("파싱된 시간: " + parsedTime);
}
}
- parse(String) 으로 LocalTime 객체 생성 가능
Duration
- 두 시간 간의 차이를 표현하는 데 사용하는 클래스
- 일, 시간, 분, 초, 나노초 단위 시간 간격 가능
- 시간 간격을 일 수, 시간, 분, 초 가능
Duration duration = Duration.between(time1, time2);
long days = duration.toDays();
long hours = duration.toHours();
long minutes = duration.toMinutes();
long seconds = duration.getSeconds();
- LocalTime, Duration 출처 : GPT