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>
最初は簡単だと思ったけど思ったより変数が多かったので迷いながら解決しました~🙂