hani:) 2023. 6. 20. 22:35

문제

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

문제 풀이

function solution(numbers, hand) {
	// 조건: 키패드를 2차원 배열로 받아드림, row & col 값으로 현재 손의 좌표 값 표시
    // 예: 1번 선택 (leftRow=0, leftCol=0)
    // 1 2 3
    // 4 5 6
    // 7 8 9
    // * 0 #

    // 1. 필요한 변수 선인 및 할당
    let leftThumb = [1, 4, 7]; // 왼손
    let rightThumb = [3, 6, 9];// 오른손
    
    let leftRow = 3, leftCol = 0;   // *
    let rightRow = 3, rightCol = 2; // #
    
    let result = "";
    
    // 2. for of문 사용하여 매개변수로 전달받은 numbers의 각 요소에 접근하여 조건에 맞게 처리
    for (num of numbers) {
    
    	// 2-1) 0에 대한 처리, 음수가 아닌 양수 값 만들기 위해 0인 경우 11로 변경
        if (num === 0) num = 11;
        
        // 2-2) 다음 row 위치 구하기, col는 왼쪽인지 오른쪽인지에 따라 지정된 값 존재
        row = Math.floor((num-1) / 3);
        
        // 2-3) 어느 손으로 키패드를 눌러야하는지 확인
        if (leftThumb.includes(num)) { // 1, 4, 7은 왼손
            leftRow = row;
            leftCol = 0;
            result += "L";
        } else if (rightThumb.includes(num)) { // 3, 6, 9는 오른손
            rightRow = row;
            rightCol = 2;
            result += "R";
        } else { // 그 외 나머지 숫자: 2 5 8 0
            let nextRow = row, nextCol = 1;
            
            let left = Math.abs(leftRow-nextRow) + Math.abs(leftCol-nextCol);	  // 다음 키보드와의 거리 찾기 (왼쪽)
            let right = Math.abs(rightRow-nextRow) + Math.abs(rightCol-nextCol);; // 다음 키보드와의 거리 찾기 (오른쪽)
            let isSame = (right==left); // 다음 키패드와의 거리가 동일한지 확인
            if (left>right || (isSame && hand==="right")){ // 오른쪽이 더 가까운 경우 오른쪽 이동
                rightRow = nextRow;
                rightCol = nextCol;
                result += "R"; 
            } else { // 왼쪽이 더 가까운 경우 왼쪽 이동
                leftRow = nextRow;
                leftCol = nextCol;
                result += "L";
            }
        }
    }
    return result;
}
728x90