[프로그래머스] 코딩테스트연습 > 키패드 누르기
알고리즘/javascript

[프로그래머스] 코딩테스트연습 > 키패드 누르기

 

코딩테스트 연습 - 키패드 누르기

[1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5] "right" "LRLLLRLLRRL" [7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2] "left" "LRLLRRLLLRR" [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] "right" "LLRLLRLLRL"

programmers.co.kr

 

function solution(numbers, hand) {
    let answer = []
    
    // 2D Array
    const keypad = {
        1: [0, 0],
        2: [0, 1],
        3: [0, 2],
        4: [1, 0],
        5: [1, 1],
        6: [1, 2],
        7: [2, 0],
        8: [2, 1],
        9: [2, 2],
        '*': [3, 0],
        0: [3, 1],
        '#': [3, 2]
    };
    
    let leftHand = keypad['*'];
    let rightHand = keypad['#'];
    
    const calDistance = (currentPos, targetPos) => {
        const row = Math.abs(currentPos[1] - targetPos[1])
        const col = Math.abs(currentPos[0] - targetPos[0])
        return row+col
    }
    
    for(let i=0; i<numbers.length; i++){
        const target = numbers[i];
        const targetPos = keypad[target]
        
        if (target === 1 || target === 4 || target === 7) {
            answer[i] = "L"
            leftHand = targetPos
        } else if(target === 3 || target === 6 || target === 9){
            answer[i] = "R"
            rightHand = targetPos
        } else {
            const leftDis = calDistance(leftHand, targetPos)
            const rightDis = calDistance(rightHand, targetPos)
            const diff = leftDis - rightDis
            
            if(diff < 0){
                answer[i] = "L"
                leftHand = targetPos
            }
            if(diff > 0){
                answer[i] = "R"
                rightHand = targetPos
            }
            if(diff === 0){
                if(hand==='left'){
                    answer[i] = "L"
                    leftHand = targetPos
                } else {
                    answer[i] = "R"
                    rightHand = targetPos                    
                }
            }
        }
    }
    
    return answer.join("")

}
  • 키패드 숫자의 각 position을 2차원으로 만들어서 거리 계산
반응형