* [프로그래머스] 키패드 누르기 - JavaScript

이은빈 EUNBIN·2021년 4월 9일
0
post-thumbnail

📌 문제

https://programmers.co.kr/learn/courses/30/lessons/67256



📌 풀이

function solution(numbers, hand) {
    function dist(num, leftHand, rightHand, pad, hand){
        const leftDist = Math.abs(pad[leftHand][0] - pad[num][0]) + 
            Math.abs(pad[leftHand][1] - pad[num][1])
        const rightDist = Math.abs(pad[rightHand][0] - pad[num][0]) + 
            Math.abs(pad[rightHand][1] - pad[num][1])

        if(leftDist === rightDist) return hand === 'left' ?  'L' : 'R';
        return leftDist < rightDist ? 'L' : 'R';
    }

    const pad = {
        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]
    };
    var leftHand = '*', rightHand = '#';
    var result = '';
    for(var num of numbers) {
        if(num % 3 === 1) {
            result += 'L';
            leftHand = num;
        } else if(num !== 0 && num % 3 === 0){
            result += 'R';
            rightHand = num;
        } else {
            result += dist(num, leftHand, rightHand, pad, hand);
            result[result.length - 1] === 'L'? leftHand = num : rightHand = num;
        }
    }

    return result;
}

출처: https://bsscl.tistory.com/47


dist 함수 샅샅이 살펴보기 살펴보기 🔥

profile
Frontend Engineer & Value Creator

0개의 댓글