카테고리 없음

[프로그래머스] (카카오 인턴) 키패드 누르기

ku-na 2022. 1. 4. 13:35

문제 설명과 제한사항

 

 

풀이

 

class Solution {
    public String solution(int[] numbers, String hand) {
        String answer = "";
        int lh = 10;
        int rh = 12;
        for(int num : numbers){
            if(num == 1||num == 4||num == 7){
                answer += "L";
                lh = num;
            }
            else if (num == 3||num == 6||num == 9){
                answer += "R";
                rh = num;
            }
            else {
                if(dis(num,lh)>dis(num,rh)){
                    answer += "R";
                    rh = num;
                }
                else if(dis(num,lh)<dis(num,rh)){
                    answer += "L";
                    lh = num;    
                }
                else {
                    if(hand.equals("right")){
                        answer += "R";
                        rh = num;
                    }
                    else if(hand.equals("left")){
                        answer += "L";
                        lh = num;
                    }
                }
            }
        }
        return answer;
    }
    
    public int dis(int pushnum, int handnum){
        int distance;
        int tmp;
        if(pushnum == 0) pushnum = 11;
        if(handnum == 0) handnum = 11;
        int pushtmp = pushnum-1;
        int handtmp = handnum -1;
        
        if(pushnum > handnum){
            tmp = pushtmp/3 - handtmp/3;
            tmp = tmp + Math.abs(pushtmp%3 - handtmp%3);
        }
        else if(pushnum < handnum){
            tmp = handtmp/3 - pushtmp/3;
            tmp = tmp + Math.abs(pushtmp%3 - handtmp%3);
        }
        else tmp = 0;
        distance = tmp;
        return distance;
    }
}

 

++

 거리를 계산하는 dis 함수를 먼저 짰다.

이 후 본문

본문 1. for each 사용 

       2. || 사용 : 멍청하게 num ==1 || 4 || 7 이렇게 쓰고 있었다.

       3. lh, rh (현재의 손 위치) 시작이 *, # 이기 때문에 시작점을 임의로 10, 12로 잡았다.

       4. 조금 더 간결하고 보기 쉽게 짜고 싶었다. 

 

dis 함수 1. 0에 손 위치를 생각해서 11로 바꾸는 걸 생각 못했다.

            2. 거리를 계산 할때 3으로 나눠 몫과 나머지의 차이로 계산 했다. 

               하지만 3을 나누면 0이 되어 거리 계산에 착오가 생기는 것을 생각 하지 못했다. 

               그래서 tmp를 만들어 1을 뺀 값으로 계산 했다.

            3. Math.abs(int a) : 정수 a (실수도 가능한듯)를 절대값으로 치환해서 반환한다.

 

생각 하지 못한 부분이 많아 굉장히 오래 걸렸다..