반응형

개선할점

HashMap 초기화 하지 않고 put 메서드 호출하려 하면 nullPointException 나므로 조심.

메서드 나누니까 편하긴 하다

import java.util.*;
class Solution {
    String mainHand;
    int[] leftPosition = {1,4};
    int[] rightPosition = {3,4};
    HashMap<Integer,int[]> phone = new HashMap<>();
    
    public String solution(int[] numbers, String hand) {
        mainHand = hand.equals("right")? "R" : "L";
        phone.put(1,new int[]{1,1});
        phone.put(2,new int[]{2,1});
        phone.put(3,new int[]{3,1});
        phone.put(4,new int[]{1,2});
        phone.put(5,new int[]{2,2});
        phone.put(6,new int[]{3,2});
        phone.put(7,new int[]{1,3});
        phone.put(8,new int[]{2,3});
        phone.put(9,new int[]{3,3});
        phone.put(0,new int[]{2,4});
        
        StringBuilder answer = new StringBuilder();
        for(int i=0;i<numbers.length;i++){
            answer.append(getHand(numbers[i]));
        }
       
        return answer.toString();
    }
    
    
    //어느 손으로 누를지 계산 -> 현재위치 이동하기
    public String getHand(int num){
        String leftOrRight = switch(num){
                case 1,4,7 -> "L";
                case 3,6,9 -> "R";
                case 2,5,8,0 -> whenMiddle(num);
                default -> mainHand;
        };
        //손 이동하기 
        makePosition(num,leftOrRight);
        
        return leftOrRight;
    }
        
    //가운데일때 어느손으로 누를지 계산
    public String whenMiddle(int num){
        int[] numPosition = phone.get(num);
        int leftHandDistance = Math.abs(leftPosition[0]-numPosition[0])
                            + Math.abs(leftPosition[1]-numPosition[1]);
        int rightHandDistance = Math.abs(rightPosition[0]-numPosition[0])
                            + Math.abs(rightPosition[1]-numPosition[1]);
    
        if(leftHandDistance == rightHandDistance){
            return mainHand;
        }else if(leftHandDistance  < rightHandDistance){
            return "L";
        }else{
            return "R";
        }
    }
    
    //현재위치 이동하기    //누를 숫자   //누를 손
    public void makePosition(int num, String whatHand){
        if(whatHand.equals("L")){
            leftPosition = phone.get(num);
        }else{
            rightPosition = phone.get(num);
        }
    }
}

//현재위치 [1,3],[2,4]이렇게
//현재위치 lefthand=4   1->1, 4->2, 7->3, *->4
//현재위치 righthand=4  3->1, 6->2, 9->3, #->4
//숫자가 1,4,7이면 -> L 
//숫자가 3,6,9이면 -> R 
//숫자가 2,5,8,0이면 2->1, 5->2, 8->3, 0->4 로 해서 가까운걸로 같으면 hand 참고
//가운데 누르고 난뒤
반응형

+ Recent posts