반응형

 

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges

 

 

 

 

 

 

 

 

 

** Javascript (+1)

 

이렇게 푸는 게 맞는 건지는 모르겠지만 어쨌든 풀었다.

 

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], 0: [3, 1]
};
const left = [1, 4, 7];
const right = [3, 6, 9];
function solution(numbers, hand) {
    let answer = "";
    let currRight = [3, 0];
    let currLeft = [3, 2];
    for (const number of numbers) {
        if (left.includes(number)) {
            answer += "L";
            currLeft = [...keypad[number]];
        }
        else if (right.includes(number)) {
            answer += "R";
            currRight = [...keypad[number]];
        } else {
            let currLoc = [...keypad[number]];
            let distanceFromLeft = Math.abs(currLoc[0] - currLeft[0]) + Math.abs(currLoc[1] - currLeft[1]);
            let distacneFromRight = Math.abs(currLoc[0] - currRight[0]) + Math.abs(currLoc[1] - currRight[1]);
            if (distanceFromLeft > distacneFromRight) {
                answer += "R";
                currRight = [...currLoc];
            }
            else if (distanceFromLeft === distacneFromRight) {
                if (hand === "right") {
                    answer += "R";
                    currRight = [...currLoc];
                } else {
                    answer += "L";
                    currLeft = [...currLoc];
                }
            }
            else {
                answer += "L";
                currLeft = [...currLoc];
            }
        }
    }
    return answer;
}
반응형

+ Recent posts