본문 바로가기

Programmers/Level1

[카카오 인턴] 키패드 누르기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Solution {
    public String solution(int[] numbers, String hand) {
        String answer = "";
        
        StringBuffer sb = new StringBuffer();
        int left_row = 4, left_col = 1, right_row = 4, right_col = 3, next_row, next_col;
        int left_dis, right_dis;
        
        for(int i=0;i<numbers.length;i++) {
            if (numbers[i] == 0) {
                next_row = 4;
                next_col = 2;
            } else {
                next_row = numbers[i] / 3 + 1;
                if (numbers[i] % 3 == 0) {
                    next_row--;
                    next_col = 3;
                }
                else
                    next_col = numbers[i] % 3;
            }
 
            if(numbers[i] == 1 || numbers[i] == 4 || numbers[i] == 7) {
                left_row = next_row;
                left_col = next_col;
                sb.append("L");
            }
            else if(numbers[i] == 3 || numbers[i] == 6 || numbers[i] == 9) {
                right_row = next_row;
                right_col = next_col;
                sb.append("R");
            }
            else {
                left_dis = Math.abs(left_row - next_row) + Math.abs(left_col - next_col);
                right_dis = Math.abs(right_row - next_row) + Math.abs(right_col - next_col);
                
                if(left_dis == right_dis){
                                        if(hand.equals("left")) {
                        left_row = next_row;
                        left_col = next_col;
                        sb.append("L");
                    } else {
                        right_row = next_row;
                        right_col = next_col;
                        sb.append("R");
                    }
                } else {
                    if(left_dis < right_dis) {
                        left_row = next_row;
                        left_col = next_col;
                        sb.append("L");
                    }
                    else {
                        right_row = next_row;
                        right_col = next_col;
                        sb.append("R");
                    }
                }
            }    
        }
        answer=sb.toString();
        
        return answer;
    }
}
cs

중복 코드만 처리해주면 더 깔끔해질 것 같다.

'Programmers > Level1' 카테고리의 다른 글

소수 찾기  (0) 2021.06.29
크레인 인형뽑기 게임  (0) 2021.06.29
약수의 개수와 덧셈  (0) 2021.06.29
신규 아이디 추천  (0) 2021.06.29
모의고사  (0) 2021.06.28