스마트폰 전화 키패드의 각 칸에 다음과 같이 숫자들이 적혀 있습니다.
이 전화 키패드에서 왼손과 오른손의 엄지손가락만을 이용해서 숫자만을 입력하려고 합니다.
맨 처음 왼손 엄지손가락은 * 키패드에 오른손 엄지손가락은 # 키패드 위치에서 시작하며, 엄지손가락을 사용하는 규칙은 다음과 같습니다.
순서대로 누를 번호가 담긴 배열 numbers, 왼손잡이인지 오른손잡이인 지를 나타내는 문자열 hand가 매개변수로 주어질 때, 각 번호를 누른 엄지손가락이 왼손인 지 오른손인 지를 나타내는 연속된 문자열 형태로 return 하도록 solution 함수를 완성해주세요.
function solution(numbers, hand) {
var answer = '';
let numpad = [[1,4,7,'*'], [2,5,8,0], [3,6,9,'#']]; // 키보드 배열 선언
let l_hand = [0,3]; // 위치 설정
let r_hand = [2,3]; // ''
function getLeft(hand, n){ // 왼쪽 구하기
let result= hand[1]-numpad[1].indexOf(n);
result = Math.abs(result);
if(hand[0]===0) result+=1;
return result;
}
function getRight(hand, n){ // 오른쪽 구하기
let result=hand[1]-numpad[1].indexOf(n);
result = Math.abs(result);
if(hand[0]===2) result+=1;
return result;
}
numbers.forEach(function(n){
let chk = 0;
if(numpad[0].includes(n)){ // 1,4,7 중에 있으면 L
answer+='L';
l_hand = [0,numpad[0].indexOf(n)];
return;
}
else if(numpad[2].includes(n)){ // 3,6,9 중에 있으면 R
answer+='R';
r_hand = [2,numpad[2].indexOf(n)];
return;
}
else{
let l_distance = getLeft(l_hand, n);
let r_distance = getRight(r_hand, n);
if(l_distance === r_distance){ // 거리가 같으면
hand === "left"? chk = 0 : chk = 1; // 왼손잡이면 0으로 오른손 잡이는 1로
}else if(l_distance<r_distance){ // 왼쪽이 더 가까우면
chk = 0; // chk는 0
}else{
chk = 1; // 오른쪽이 더 가까울 시 1
}
if(chk === 0){ // chk가 0이면 왼손 움직이기
answer +='L';
l_hand = [1,numpad[1].indexOf(n)];
}else{ // 1일 경우 오른손으로!
answer +='R';
r_hand = [1,numpad[1].indexOf(n)];
}
}
})
return answer;
}
정확성: 100.0
합계: 100.0 / 100.0
[프로그래머스/JS] Lv2. 카펫 (0) | 2021.04.26 |
---|---|
[프로그래머스/JS] Lv2. 올바른 괄호 (0) | 2021.04.25 |
[프로그래머스/JS] Lv1. 체육복 (0) | 2021.04.23 |
[프로그래머스/JS] Lv1. 음양 더하기 (0) | 2021.04.23 |
[프로그래머스/JS] Lv1. 실패율 (0) | 2021.04.22 |
댓글 영역