본문 바로가기
알고리즘

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

by limew 2023. 5. 28.

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

 

  • 현재 오른쪽, 왼쪽 손가락의 위치를 매번 이동후에 갱신해야한다 currLeft, currRight
  • 1~9까지 정해진 위치,  손을 obj 로 config 해서, 한번에 위치를 파악할 수 있다 (되도록 확장하기 편하게 만들자. 특수적인 공식%으로 가독성을 해하지말고)
  • 맨하튼 거리: Math.abs(start[0] - end[0]) + Math.abs(start[1] - end[1])
function manhattanDist(start, end) {
    return Math.abs(start[0] - end[0]) + Math.abs(start[1] - end[1]);
}

function solution(numbers, hand) {
    var answer = '';
    let currLeft = [3, 0]; // 왼손위치
    let currRight = [3, 2]; // 오른손위치
    const obj = {
        1: {hand: 'L', pos: [0,0]}, // LEFT
        2: {hand: 'C', pos: [0,1]}, // CENTER
        3: {hand: 'R', pos: [0,2]}, // RIGHT
        4: {hand: 'L', pos: [1,0]},
        5: {hand: 'C', pos: [1,1]},
        6: {hand: 'R', pos: [1,2]},
        7: {hand: 'L', pos: [2,0]},
        8: {hand: 'C', pos: [2,1]},
        9: {hand: 'R', pos: [2,2]},
        0: {hand: 'C', pos: [3,1]},
    }
   
    for (const number of numbers) {
        const target = obj[number];
        let selectedHand;
        
        // 센터
        if (target.hand === 'C') {
            const leftDistance = manhattanDist(currLeft, target.pos);
            const rightDistance = manhattanDist(currRight, target.pos);
            // 거리가 같으면 어느 손잡이인지
            if (leftDistance === rightDistance) {
                selectedHand = (hand === 'right') ? 'R' : 'L';
            } 
            // 거리가 짧은 손
            else {
                selectedHand = (leftDistance < rightDistance) ? 'L' : 'R';
            }
        }
        // !센터
        else {
            selectedHand = target.hand;
        }
        answer += selectedHand;
        if (selectedHand === 'L') {
            currLeft = target.pos;
        } else {
            currRight = target.pos;
        }
    }
    return answer;
}