본문 바로가기
미분류/취준

[PGMRS / Java] 개인정보 수집 유효기간

by 껐다 켜보셨어요? 2024. 12. 25.

문제 복붙하기 귀찮다

https://school.programmers.co.kr/learn/courses/30/lessons/150370#

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

전체 코드

import java.util.*;

class Solution {
    static HashMap<String, Integer> termMap;
    
    static class TermDate implements Comparable<TermDate> { 
        // 비교, month연산 가능한 날짜 클래스
        int year, month, date;
        TermDate(String date) {
            String[] splited = date.split("\\.");
            try {
                this.year = Integer.parseInt(splited[0]);
                this.month = Integer.parseInt(splited[1]);
                this.date = Integer.parseInt(splited[2]);
            }catch(Exception e){
                this.year = this.month = this.date = 0;
            }
        }
        
        public TermDate dueDate(int months) { // 유통기한(?) 날짜 리턴
            TermDate result = this;
            if(result.month + months > 12) {
                result.year += (result.month + months) / 12;
                result.month = (result.month + months) % 12;
                if(result.month == 0) {
                	result.year--;
                	result.month = 12;
                }
            } else {
                result.month = result.month + months;
            }
            return result;
        }
        
        @Override
        public int compareTo(TermDate other) {
            if(this.year == other.year){
                if(this.month == other.month){
                    if(this.date == other.date){
                        return 0; // 같은 날짜임
                    }
                    return Integer.compare(this.date, other.date);
                }
                return Integer.compare(this.month, other.month);
            }
            return Integer.compare(this.year, other.year);
        }
    }
    
    public void mapSetter (String[] termsList) { // static HashMap terms를 초기화
        termMap = new HashMap<>();
        for(String term : termsList) {
            String[] splited = term.split(" ");
            try {
                termMap.put(splited[0], Integer.parseInt(splited[1]));
            } catch(Exception e){
                termMap.put(splited[0], 0);
            }
        }
    }
    
    public int[] parser (Object[] array) {
        int[] result = new int[array.length];
        for(int i = 0; i<array.length; i++) {
            try {
                result[i] = (int) array[i];
            } catch(Exception e){
                result[i] = 0;
            }
        }
        return result;
    }
    
    public int[] solution(String today, String[] terms, String[] privacies) {
        ArrayList<Integer> answer = new ArrayList<>();
        
        TermDate td = new TermDate(today);
        mapSetter(terms);
        
        for(int i = 0; i<privacies.length; i++){
            TermDate dueDate = new TermDate(privacies[i].split(" ")[0]).dueDate(termMap.get(privacies[i].split(" ")[1]));
            if(td.compareTo(dueDate) >= 0) answer.add(i+1);
        }
        
        return parser(answer.toArray());
    }
}

 

 

출력, main함수 포함된 디버깅 코드

더보기
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class PRGMRS_개인정보수집유효기간 {
	// 풀이가 아닌 디버깅 코드입니다.
	static HashMap<String, Integer> termMap;
    
    static class TermDate implements Comparable<TermDate> { 
        // 비교, month연산 가능한 날짜 클래스
        int year, month, date;
        TermDate(String date) {
            String[] splited = date.split("\\.");
            try {
                this.year = Integer.parseInt(splited[0]);
                this.month = Integer.parseInt(splited[1]);
                this.date = Integer.parseInt(splited[2]);
            }catch(Exception e){
                this.year = this.month = this.date = 0;
            }
        }
        
        public TermDate dueDate(int months) { // 유통기한(?) 날짜 리턴
            TermDate result = this;
            if(result.month + months > 12) {
                result.year += (result.month + months) / 12;
                result.month = (result.month + months) % 12;
                if(result.month == 0) {
                	result.year--;
                	result.month = 12;
                }
            } else {
                result.month = result.month + months;
            }
            return result;
        }
        
        @Override
        public int compareTo(TermDate other) {
            if(this.year == other.year){
                if(this.month == other.month){
                    if(this.date == other.date){
                        return 0; // 같은 날짜임
                    }
                    return Integer.compare(this.date, other.date);
                }
                return Integer.compare(this.month, other.month);
            }
            return Integer.compare(this.year, other.year);
        }
        
        public void printOut() {
        	System.out.printf("%d.%d.%d\n", this.year, this.month, this.date);
        }
    }
    
    public static void mapSetter (String[] termsList) { // static HashMap terms를 초기화
        termMap = new HashMap<>();
        for(String term : termsList) {
            String[] splited = term.split(" ");
            try {
                termMap.put(splited[0], Integer.parseInt(splited[1]));
            } catch(Exception e){
                termMap.put(splited[0], 0);
            }
        }
    }
    
    public static int[] parser (Object[] array) {
        int[] result = new int[array.length];
        for(int i = 0; i<array.length; i++) {
            try {
                result[i] = (int) array[i];
            } catch(Exception e){
                result[i] = 0;
            }
        }
        return result;
    }
    
    public static int[] solution(String today, String[] terms, String[] privacies) {
        ArrayList<Integer> answer = new ArrayList<>();
        
        TermDate td = new TermDate(today);
        mapSetter(terms);
        
        //debug
        System.out.println("===============================");
        td.printOut();
        
        for(int i = 0; i<privacies.length; i++){
            TermDate dueDate = new TermDate(privacies[i].split(" ")[0]).dueDate(termMap.get(privacies[i].split(" ")[1]));
            dueDate.printOut();
            if(td.compareTo(dueDate) >= 0) answer.add(i+1);
        }
        
        return parser(answer.toArray());
    }
    
    // 이하 테스트코드
    static class TestCase {
    	String today;
    	String[] terms, privacies;
    	
    	TestCase(String today, String[] terms, String[] privacies) {
    		this.today = today;
    		this.terms = terms;
    		this.privacies = privacies;
    	}
    }
    
	public static void main(String[] args) {
		
		TestCase[] tc = {
			 new TestCase(
	            "2022.05.19",
	            new String[] { "A 6", "B 12", "C 3" },
	            new String[] { "2021.05.02 A", "2021.07.01 B", "2022.02.19 C", "2022.02.20 C" }
	        ),
			 new TestCase(
					 "2020.01.01",
					 new String[] { "Z 3", "D 5" },
					 new String[] { "2019.01.01 D", "2019.11.15 Z", "2019.08.02 D", "2019.07.01 D", "2018.12.28 Z" }
					 ),
			 new TestCase(
					 "2009.12.28",
					 new String[] { "A 13" },
					 new String[] { "2008.11.03 A", "2007.02.03 A" }
					 ),
		};
		
		for(TestCase t : tc) {
			System.out.println(Arrays.toString(solution(t.today, t.terms, t.privacies)));
			
		}
	}

}

 

===============================

2022.5.19

2021.11.2

2022.7.1

2022.5.19

2022.5.20

[1, 3]

===============================

2020.1.1

2019.6.1

2020.2.15

2020.1.2

2019.12.1

2019.3.28

[1, 4, 5]

===============================

2009.12.28

2009.12.3

2008.3.3

[1, 2]

 

나는 요렇게 포맷이 정해진 ... 구조화할 껀덕지가 있는 문제는 꼭 클래스를 써서 구조를 잡아주곤 하는데

특히 뭔가 비교할 게 있으면 얼씨구 Comparable 써먹는 걸 참 좋아한다

그래서인지 구현 쪽 문제들이 풀이가 재밌음

테스트 1 통과 (0.58ms, 70MB)
테스트 2 통과 (0.52ms, 81.7MB)
테스트 3 통과 (0.50ms, 93.9MB)
테스트 4 통과 (0.48ms, 75.7MB)
테스트 5 통과 (0.53ms, 76.2MB)
테스트 6 통과 (0.61ms, 82.1MB)
테스트 7 통과 (0.54ms, 71.2MB)
테스트 8 통과 (0.94ms, 75.9MB)
테스트 9 통과 (1.18ms, 84.4MB)
테스트 10 통과 (0.90ms, 81MB)
테스트 11 통과 (0.86ms, 74.5MB)
테스트 12 통과 (1.33ms, 78.5MB)
테스트 13 통과 (2.14ms, 86.2MB)
테스트 14 통과 (0.93ms, 75.9MB)
테스트 15 통과 (0.94ms, 89.7MB)
테스트 16 통과 (1.40ms, 81.6MB)
테스트 17 통과 (1.43ms, 73.2MB)
테스트 18 통과 (1.48ms, 73.7MB)
테스트 19 통과 (1.71ms, 95.1MB)
테스트 20 통과 (1.59ms, 74.9MB)

 

오랜만에 자바 재활 했다

속도는 좀 느린 듯하지만 코드는 그럭저럭 짠 것 같은데

시간 날 때 JS 풀이도 붙이도록 하겠음

물론 그때도 class 써먹을 예정

 

try-catch에서 예외처리 값을 대충 0으로 때려박은 거랑

if(result.month + months > 12) {

  result.year += (result.month + months) / 12;

  result.month = (result.month + months) % 12;

  if(result.month == 0) { // 이 부분.

    result.year--;

    result.month = 12;

  }

} else {

  result.month = result.month + months;

}

표시한 부분 코드가 좀 아쉽다 

근데 코드 주절주절 늘리지 않고 짧게 쓰자니 그건 그것대로 연산을 더 하게 되는 꼴 or 변수 더 만드는 꼴이었어서

연산 더 시키느니 코드 늘리는 게 낫다고 판단함 

 

++ 

아 맞다 이 얘기 하려고 했는데 ...

처음에 저 표시한 부분 없이 로직 짜고 제출했더니 17번 케이스에서만 틀려서

뭐지? 하고 생각해봤더니

month%12가 0이 되는 경우를 생각하지 못해서 그런 거였다.

나머지 연산으로 풀고 있고, 17번 케이스만 틀린다면 높은 확률로 0월 때문

ㅋㅋㅋㅋㅋㅋ

비슷한 풀이와 예외케이스로 틀렸던 문제가 있는데 백준의 ACM 호텔이라고 있다

https://nogotit.tistory.com/entry/BOJ-10250ACM-%ED%98%B8%ED%85%94

 

BOJ 10250_ACM 호텔

문제ACM 호텔 매니저 지우는 손님이 도착하는 대로 빈 방을 배정하고 있다. 고객 설문조사에 따르면 손님들은 호텔 정문으로부터 걸어서 가장 짧은 거리에 있는 방을 선호한다고 한다. 여러분은

nogotit.tistory.com

 

'미분류 > 취준' 카테고리의 다른 글

또 근황  (2) 2025.04.06
근황  (0) 2025.03.17
[Grind75 / TypeScript, Java] #2 Valid Parentheses  (0) 2024.10.22
[Grind75 / TypeScript, Java] #1 Two Sum  (2) 2024.10.22
알고리즘 공부할 것 리스트  (0) 2024.10.16

댓글