섹션2. 해싱 & 시간 파싱 알고리즘 - (4)

728x90

🎈섹션2. 해싱 & 시간 파싱 알고리즘 - (4)

🟦 2-6. 문서 도난

⬛ 문자열 (알파벳 순으로 ) 비교하는 compareTo() 사용법

  • A.compareTo(B)
  • 1) A 가 B보다 앞순이면 음수 출력
  • 2) A 가 B보다 뒷순이면 양수 출력
  • 3) A== B순이면 0 출력

시간 파싱 HH:MM → 분 단위로 변환하여 비교할 것

  • getTime(String HH:MM) 함수 만들어서 들어온 입력을 → 분 단위로 변환시킴
  • HH:MM 단위로 들어온 String은 split(”:”) 기준으로 잘라서 앞은 HH, 뒤는 MM
//시간 -> 분 단위 변형 함수
    public int getTime(String time) {
        int H = Integer.parseInt(time.split(":")[0]);
        int M = Integer.parseInt(time.split(":")[1]);

        return 60*H + M;
    }

나의 첫 시도 |

  • 어쨋든 times 이내에 속한 사람들 뽑는 것은 성공했는데,
  • 그 사람들을 시간 앞순으로 뽑는 것을 못했다.ㅠㅠ
  • 내가 최초에 생각했던 풀이는 다음과 같다.
  • 1) 우선 HashMap에 입력값으로 들어오는 <사람이름, HH:MM> 값을 담는다.
  • 2) times 구간 이내로 HH:MM이 속해있는지 확인
  • → 여기서 나는 String의 문자 순서 1,2,3이 4,5,6,보다 앞순서인 것을 생각해서, 구간 안에 속하는지 확인했다.
  • 3) 결과적으로 times 구간 내에 속해있는 사람들 뽑는 것은 가능했는데, 그 사람들 끼리 시간 앞순 정렬하기 까다로워서 포기했다.

첫 시도 코드

package to_0427;

/* 2-6. 문서 도난
 * */
import java.util.*;
class Solution2 {
    public String[] solution(String[] reports, String times){
        String[] answer = {};
        HashMap<String, String> Rmap = new HashMap<>();
        //1) 담기 
        for(String x : reports) {
            String a = x.split(" ")[0];
            String b = x.split(" ")[1];
            Rmap.put(a, b);
        }
        //String 끼리 사전 순 비교하기 : compareTo()
        String start = times.split(" ")[0];
        String end = times.split(" ")[1];

        String tmp = "";
        //2) 하나씩 뽑으면서 times 구간 이내 값인지 사전 순 비교 후 이름 뽑기
        for(String key : Rmap.keySet()) {
            //start보다 key의 값이 뒷순서이면서(양수) && end보다는 key의 값이 앞순서일 떄(음수)
            if(Rmap.get(key).compareTo(start) >=0 && Rmap.get(key).compareTo(end) <=0) {
                tmp += key + " ";
            }
        }

        //3) 이제 tmp에 담긴 각 값을 map에서 찾은 뒤 그 value가 더 앞서는 순으로 answer에 담기 
        answer = tmp.split(" ");

        return answer;
    }

    public static void main(String[] args){
        Solution2 T = new Solution2();
        System.out.println(Arrays.toString(T.solution(new String[]{"john 15:23", "daniel 09:30", "tom 07:23", "park 09:59", "luis 08:57"}, "08:33 09:45")));
        System.out.println(Arrays.toString(T.solution(new String[]{"ami 12:56", "daniel 15:00", "bob 19:59", "luis 08:57", "bill 17:35", "tom 07:23", "john 15:23", "park 09:59"}, "15:01 19:59")));
        System.out.println(Arrays.toString(T.solution(new String[]{"cody 14:20", "luis 10:12", "alice 15:40", "tom 15:20", "daniel 14:50"}, "14:20 15:20")));
    }
}

완성 코드

  • 새로운 Info객체를 생성해주고 이 객체는 <name, time> 담는다.
  • compareTo() 를 재정의하여 ‘시간’ 기준으로 오름차순 정렬
  • → Collections.sort(배열) 시, 자동 시간 기준으로 정렬됨
  • [HH:MM] → 모두 분 단위 시간으로 변환해준다.
  • times 값 도 분 단위 시간으로 변환 후 그 구간 내에 속하는 사람들만 이름을 뽑아서 arrayList에 담아두고, answer는 ArrayList 크기와 동일하게 생성한 뒤 순서대로 옮겨준다.
package to_0427;
/* 2-6. 문서 도난 다시 풀이 */
import java.util.*;
class Info implements Comparable<Info>{
    public String name;
    public int time;

    //생성자
    Info(String name, int time){
        this.name= name;
        this.time=time;
    }
    //비교 연산자 
    @Override
    public int compareTo(Info o) {
        // TODO Auto-generated method stub
        //'시간' 기준 오름차순 정렬 
        //cf. 내림차순은 o.time-this.time; 하면 된다. 
        return this.time -o.time;
    }
}

class Solution2_Re {
    //getTime: 시간 파싱 함수 HH:MM 을 분단위로 변환하는 함수 
    public int getTime(String time) {
        int H = Integer.parseInt(time.split(":")[0]);
        int M = Integer.parseInt(time.split(":")[1]);
        return H*60 + M;//분 단위로 변형
    }

    //솔루션 함수 
    public String[] solution(String[] reports, String times){

        ArrayList<Info> tmp = new ArrayList<>();
        for(String x : reports) {
            String a = x.split(" ")[0]; //사람 이름 
            String b = x.split(" ")[1];
            tmp.add(new Info(a, getTime(b)));
        }

        //'시간'기준 오름차순 정렬 (compareTo())
        Collections.sort(tmp);

        //times 구간도 분 단위로 변환
        int s = getTime(times.split(" ")[0]);
        int e = getTime(times.split(" ")[1]);

        //시간 구간 내에 속하는 사람만 뽑기 
        ArrayList<String> res = new ArrayList<>();
        for(Info ob : tmp) {
            if(ob.time >= s && ob.time <=e) {
                res.add(ob.name);
            }
            if(ob.time > e) break; //아 시간 순 정렬 했으니까 e 초과하면 그냥 멈춤
        }

        //size를 잡아주고 해야 에러가 안난다.
        String[] answer = new String[res.size()];
        for(int i=0; i<res.size(); i++){
            answer[i] = res.get(i);
        }

        return answer;
    }
    //실행 메인 
    public static void main(String[] args){
        Solution2_Re T = new Solution2_Re();
        System.out.println(Arrays.toString(T.solution(new String[]{"john 15:23", "daniel 09:30", "tom 07:23", "park 09:59", "luis 08:57"}, "08:33 09:45")));
        System.out.println(Arrays.toString(T.solution(new String[]{"ami 12:56", "daniel 15:00", "bob 19:59", "luis 08:57", "bill 17:35", "tom 07:23", "john 15:23", "park 09:59"}, "15:01 19:59")));
        System.out.println(Arrays.toString(T.solution(new String[]{"cody 14:20", "luis 10:12", "alice 15:40", "tom 15:20", "daniel 14:50"}, "14:20 15:20")));
    }
}

다시 품 코드 (복습)

package to_0427;
/* 2-6. 문서 도난 다시 풀기 
 * */
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
class Info1 implements Comparable<Info1>{
    String name; 
    int time;

    Info1(String name, int time){
        this.name = name;
        this.time = time;
    }
    @Override
    public int compareTo(Info1 o) {
        // TODO Auto-generated method stub
        //시간 기준 오름차순 정렬
        return this.time - o.time;
    }
}

class Solution {
    //시간 -> 분 단위 변형 함수
    public int getTime(String time) {
        int H = Integer.parseInt(time.split(":")[0]);
        int M = Integer.parseInt(time.split(":")[1]);

        return 60*H + M;
    }

    //솔루션 함수 
    public String[] solution(String[] reports, String times){
        //1) 우선 규격 맞춰서 담기 
        ArrayList<Info> arr = new ArrayList<>();
        for(String x : reports) {
            String a = x.split(" ")[0]; //사람
            String b = x.split(" ")[1]; //시간

            arr.add(new Info(a, getTime(b)));
        }

        //시간 기준 오름차순 정렬
        Collections.sort(arr);

        //2) time 구간 이내값만 이름뽑기 
        ArrayList<String> List = new ArrayList<>();

        int s= getTime(times.split(" ")[0]);
        int e = getTime(times.split(" ")[1]);

        for(Info x : arr) {
            if(x.time >= s && x.time <= e) {
                List.add(x.name);
            }
            if(x.time > e) break; //시간 순 정렬되어 있으므로 넘어가면 그냥 돌지 말고 멈췀
        }
        //3) 답 세팅 
        String[] answer = new String[List.size()];
        for(int i=0; i<List.size(); i++) {
            answer[i]= List.get(i);
        }

        return answer;
    }

    public static void main(String[] args){
        Solution T = new Solution();
        System.out.println(Arrays.toString(T.solution(new String[]{"john 15:23", "daniel 09:30", "tom 07:23", "park 09:59", "luis 08:57"}, "08:33 09:45")));
        System.out.println(Arrays.toString(T.solution(new String[]{"ami 12:56", "daniel 15:00", "bob 19:59", "luis 08:57", "bill 17:35", "tom 07:23", "john 15:23", "park 09:59"}, "15:01 19:59")));
        System.out.println(Arrays.toString(T.solution(new String[]{"cody 14:20", "luis 10:12", "alice 15:40", "tom 15:20", "daniel 14:50"}, "14:20 15:20")));
    }
}

🟦 2-7. 경고 메일

문제 풀이

최초 시도 코드 |

package to_0427_1;
/* 2-7. 경고 메일 풀기 */
import java.util.*;
class Info {
    String name;
    int time;
    String state;

    Info(String name, int time, String state){
        this.name = name;
        this.time = time;
        this.state = state;
    }
}
class Solution3 {
    //시간 분 함수
    public int getTime(String time) {
        int H = Integer.parseInt(time.split(":")[0]);
        int M = Integer.parseInt(time.split(":")[1]);

        return H*60 + M;
    }

    //솔루션 함수 
    public String[] solution(String[] reports, int time){
        //객체 단위로 일단 담기
        ArrayList<Info> arr = new ArrayList<>();

        for(String x : reports) {
            String a = x.split(" ")[0];
            String b = x.split(" ")[1];
            String c = x.split(" ")[2];

            arr.add(new Info(a, getTime(b), c));
        }

        HashMap<String, Integer> inT = new HashMap<>();
        //time 계싼 
        for(Info x : arr) {
            if(x.state == "in") { //들어오는 애 
                inT.put(x.name, x.time);
            }
        }
        //sum
        HashMap<String, Integer > sumT = new HashMap<>();
        for(Info x : arr) {
            if(x.state == "out") {
                sumT.put(x.name, x.time - inT.get(x.name));
            }
        }

        ArrayList<String> tmp = new ArrayList<>();

        for(String key : sumT.keySet()) {
            if(sumT.get(key) > time) {
                tmp.add(key);
            }
        }
        Collections.sort(tmp);

        String[] answer = new String[tmp.size()];
        for(int i=0; i<tmp.size(); i++) {
            answer[i] = tmp.get(i);
        }

        return answer;
    }

    public static void main(String[] args){
        Solution3 T = new Solution3();
        System.out.println(Arrays.toString(T.solution(new String[]{"john 09:30 in", "daniel 10:05 in", "john 10:15 out", "luis 11:57 in", "john 12:03 in", "john 12:20 out", "luis 12:35 out", "daniel 15:05 out"}, 60)));    
        System.out.println(Arrays.toString(T.solution(new String[]{"bill 09:30 in", "daniel 10:00 in", "bill 11:15 out", "luis 11:57 in", "john 12:03 in", "john 12:20 out", "luis 14:35 out", "daniel 14:55 out"}, 120)));
        System.out.println(Arrays.toString(T.solution(new String[]{"cody 09:14 in", "bill 09:25 in", "luis 09:40 in", "bill 10:30 out", "cody 10:35 out", "luis 10:35 out", "bill 11:15 in", "bill 11:22 out", "luis 15:30 in", "luis 15:33 out"}, 70)));
        System.out.println(Arrays.toString(T.solution(new String[]{"chato 09:15 in", "emilly 10:00 in", "chato 10:15 out", "luis 10:57 in", "daniel 12:00 in", "emilly 12:20 out", "luis 11:20 out", "daniel 15:05 out"}, 60)));
    }
}

완성 코드

package to_0427;
/* 2-6. 문서 도난 다시 풀이 */
import java.util.*;
class Info implements Comparable<Info>{
    public String name;
    public int time;

    //생성자
    Info(String name, int time){
        this.name= name;
        this.time=time;
    }
    //비교 연산자 
    @Override
    public int compareTo(Info o) {
        // TODO Auto-generated method stub
        //'시간' 기준 오름차순 정렬 
        //cf. 내림차순은 o.time-this.time; 하면 된다. 
        return this.time -o.time;
    }
}

class Solution2_Re {
    //getTime: 시간 파싱 함수 HH:MM 을 분단위로 변환하는 함수 
    public int getTime(String time) {
        int H = Integer.parseInt(time.split(":")[0]);
        int M = Integer.parseInt(time.split(":")[1]);
        return H*60 + M;//분 단위로 변형
    }

    //솔루션 함수 
    public String[] solution(String[] reports, String times){

        ArrayList<Info> tmp = new ArrayList<>();
        for(String x : reports) {
            String a = x.split(" ")[0]; //사람 이름 
            String b = x.split(" ")[1];
            tmp.add(new Info(a, getTime(b)));
        }

        //'시간'기준 오름차순 정렬 (compareTo())
        Collections.sort(tmp);

        //times 구간도 분 단위로 변환
        int s = getTime(times.split(" ")[0]);
        int e = getTime(times.split(" ")[1]);

        //시간 구간 내에 속하는 사람만 뽑기 
        ArrayList<String> res = new ArrayList<>();
        for(Info ob : tmp) {
            if(ob.time >= s && ob.time <=e) {
                res.add(ob.name);
            }
            if(ob.time > e) break; //아 시간 순 정렬 했으니까 e 초과하면 그냥 멈춤
        }

        //size를 잡아주고 해야 에러가 안난다.
        String[] answer = new String[res.size()];
        for(int i=0; i<res.size(); i++){
            answer[i] = res.get(i);
        }

        return answer;
    }
    //실행 메인 
    public static void main(String[] args){
        Solution2_Re T = new Solution2_Re();
        System.out.println(Arrays.toString(T.solution(new String[]{"john 15:23", "daniel 09:30", "tom 07:23", "park 09:59", "luis 08:57"}, "08:33 09:45")));
        System.out.println(Arrays.toString(T.solution(new String[]{"ami 12:56", "daniel 15:00", "bob 19:59", "luis 08:57", "bill 17:35", "tom 07:23", "john 15:23", "park 09:59"}, "15:01 19:59")));
        System.out.println(Arrays.toString(T.solution(new String[]{"cody 14:20", "luis 10:12", "alice 15:40", "tom 15:20", "daniel 14:50"}, "14:20 15:20")));
    }
}

728x90