Lv.1 키패드 누르기

🤖문제

👍 2022년 1월 20일

<script>
function moveCount(diff) {
    if (diff === 0) return 0;
    else if  (diff === 1 || diff === 3) return 1;
    else if (diff===2 || diff===4||diff===6) return 2;
    else if (diff === 5 || diff === 7 || diff ===9) return 3;
    else return 4;
}

function solution(numbers, hand) {
    var answer = '';
    let rightPosition = 12; 
    let leftPosition = 10;
    
    for (let n of numbers) {
        if (n===1 || n===4 || n=== 7) {
            answer += "L";
            leftPosition = n;
        } else if (n===3 || n===6 || n===9) {
            answer += "R";
            rightPosition = n;
        } else {
            if (n === 0) n = 11; 
            let rightDistance = moveCount(Math.abs(rightPosition-n));
            let leftDistance =  moveCount(Math.abs(leftPosition-n));
            
            if (rightDistance < leftDistance) {
                answer += "R"; 
                rightPosition = n;
            }
            else if (leftDistance < rightDistance) {
                answer += "L";
                leftPosition = n;
            }
            else {
                hand === "right" 
                ? (answer += "R", rightPosition=n )
                : (answer += "L", leftPosition=n)
            }
        }
    }
    
    return answer;
}
</script>

처음엔 쉽다고 생각했는데 생각보다 변수가 많아서 좀 헤맸지만 해결~🙂

좋은 웹페이지 즐겨찾기