TIL

개인정보 수집 유효기간, 과제 진행하기

정유감 2023. 11. 30. 20:21
728x90
반응형

2023년 11월 30일 TIL

2주차 미션을 하면서 Date타입을 다뤄본적이 있었다.
언제 또 써먹게 되려나 싶었는데 알고리즘을 풀며 다시 써먹게 되었다.    

개인정보 수집 유효기간

전체 코드

    public int[] solution76(String today, String[] terms, String[] privacies) {
        List<Integer> answer = new ArrayList<>();

        String[][] termsArray = new String[terms.length][2];
        String[][] privaciesArray = new String[privacies.length][4];

        for (int i = 0; i < terms.length; i++) {
            termsArray[i] = terms[i].split(" ");
        }

        for (int i = 0; i < privacies.length; i++) {
            privaciesArray[i][0] = String.valueOf(privacies[i].charAt(11));
            privaciesArray[i][1] = privacies[i].substring(0, 10); // 날짜 문자열 직접 저장
        }

        for (int i = 0; i < privaciesArray.length; i++) {
            for (int j = 0; j < termsArray.length; j++) {
                if (privaciesArray[i][0].equals(termsArray[j][0])) { 
                    if (checkDDay(today, termsArray[j], privaciesArray[i][1]))
                        answer.add(i + 1);
                }
            }
        }

        int[] answerArray = new int[answer.size()];
        for (int i = 0; i < answer.size(); i++)
            answerArray[i] = answer.get(i);

        return answerArray;
    }

    public boolean checkDDay(String today, String[] termsArray, String privaciesDateStr) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd");
        LocalDate todayDate = LocalDate.parse(today, formatter);
        LocalDate privacyDate = LocalDate.parse(privaciesDateStr, formatter);

        int monthsToAdd = Integer.parseInt(termsArray[1]);
        LocalDate expiryDate = privacyDate.plusMonths(monthsToAdd);

        return expiryDate.isBefore(todayDate) || expiryDate.isEqual(todayDate);
    }
public boolean checkDDay(String today, String[] termsArray, String privaciesDateStr) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd");
        LocalDate todayDate = LocalDate.parse(today, formatter);
        LocalDate privacyDate = LocalDate.parse(privaciesDateStr, formatter);

        int monthsToAdd = Integer.parseInt(termsArray[1]);
        LocalDate expiryDate = privacyDate.plusMonths(monthsToAdd);

        return expiryDate.isBefore(todayDate) || expiryDate.isEqual(todayDate);
    }

날짜를 String으로 넣어줘서 어떻게 처리할까 하다 DateTimeFormatter가 생각나 시도해봤다.

today
"2022.05.19"    

terms
["A 6", "B 12", "C 3"]

privacies
["2021.05.02 A", "2021.07.01 B", "2022.02.19 C", "2022.02.20 C"]

result
[1, 3]

today 로 들어오는 "2022.05.19" 나, 'privacies'를 subString 으로 만드는 "2021.05.02"

둘 다 형태가 날짜이므로

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd");

형태와 같은 String이 들어올때 Date로 바꿔주어 이용할 수 있었다.

과제 진행하기

전체 코드
    public int returnMinute(String s) {
        String[] parts = s.split(":");
        return Integer.parseInt(parts[0]) * 60 + Integer.parseInt(parts[1]);
    }

    public String[] solution78_1(String[][] plans) {
        List<Plan> planList = new ArrayList<>();

        List<String> answerList = new ArrayList<>();
        Stack<Plan> pausedPlans = new Stack<>();


        for (String[] p : plans) {
            planList.add(new Plan(p[0],
                    returnMinute(p[1]),
                    Integer.parseInt(p[2])));
        }


        planList.sort(Comparator.comparingInt(p -> p.timeInMinute));
        int currentTime = planList.get(0).timeInMinute;

        for (int i = 0; i < planList.size(); i++) {
            Plan currentPlan = planList.get(i);

            while (currentTime < currentPlan.timeInMinute) {
                if (!pausedPlans.isEmpty()) {
                    Plan pausedPlan = pausedPlans.pop();
                    pausedPlan.duration--;
                    if (pausedPlan.duration == 0)
                        answerList.add(pausedPlan.subject);
                    else
                        pausedPlans.push(pausedPlan);                
                }
                currentTime++;
            }

            while (currentPlan.duration > 0
                    && (i == planList.size() - 1 
  || currentTime < planList.get(i + 1).timeInMinute)) {
                currentPlan.duration--;
                currentTime++;
            }
            if (currentPlan.duration == 0)
                answerList.add(currentPlan.subject);
            else
                pausedPlans.push(currentPlan);        
        }


        while (!pausedPlans.isEmpty()) {
            Plan pausedPlan = pausedPlans.pop();
            answerList.add(pausedPlan.subject);
        }

        String[] answer = new String[answerList.size()];
        for (int i = 0; i < answer.length; i++)
            answer[i] = answerList.get(i);

        return answer;
    }

    class Plan {
        String subject;
        int timeInMinute;
        int duration;


        public Plan(String subject, int timeInMinute, int duration) {
            this.subject = subject;
            this.timeInMinute = timeInMinute;
            this.duration = duration;

        }
    }
알고리즘을 풀면서 처음으로 객체를 생성해 풀었는데
알고리즘 스터디를 하면서 듣자하니 `List<Object>` 를 이용하면
해당 객체 안에 `int`와 (정확히는 `Integer`) `String`을 함께 담을 수 있단다.
다음엔 그렇게 해보기로 하고. 

다른 문제를 풀다보니 이곳에서도 String으로 들어오는 시간을 변환해서 이용해야 했다.
아래와 같이 들어오는 String[]을 시간으로 이용하기 위해

          "korean", "11:40", "30"

split으로 나눠주어 분으로 만들어 반환했다.

    public int returnMinute(String s) {
        String[] parts = s.split(":");
        return Integer.parseInt(parts[0]) * 60 + Integer.parseInt(parts[1]);
    }

결론

String 으로 들어오는 시간 개념은 이제 어느정도 해결할 수 있다는 자신감이 생긴다.
또한 요새 splitreplace 같은 메서드들의 유용성에도 주목하고 있다.
특히 splitc언어로 직접 구현할 때 나를 괴롭혔던 녀석이라
어렵게 잡은 포켓몬을 잘 쓰고 있는 기분이다.

728x90
반응형