다른 사람 풀이를 보니 diff 값을 맵으로 만든 다음 간단히 계산하던데, 역시 능력자들이 많네.
모든 프로그래머스 문제 관련 코드들은 GitHub 링크 에 있음.
function solution(numbers, hand) {
let result = '';
// 현재 위치와 목표 위치간의 diff 계산해서 리턴
// * 은 10 으로, 0 은 11 로, # 은 12 로 간주하고 계산
const getDiff = (current, target) => {
let diff = 0;
// Math.abs(current - target) 3 이상인 경우에는 행 이동을 해야하고 (+- 3 을 해야함), 행 이동 횟수가 diff 에 포함
if (Math.abs(current - target) >= 3) {
if (current > target) {
diff = Math.floor((current - target) / 3);
current = current - (3 * diff);
} else {
diff = Math.floor((target - current) / 3);
current = current + (3 * diff);
}
}
// Math.abs(current - target) 의 결과값이 3 미만인 경우 -> 결과값이 그대로 현재 current 와 target 간 거리이므로 diff 에 포함
if (Math.abs(current - target) > 0) {
diff += Math.abs(current - target);
}
return diff;
};
let leftPosition = 10;
let rightPosition = 12;
numbers
.map(n => n === 0 ? 11 : n)
.map(n => {
let useHand = 'L';
if (n === 1 || n === 4 || n === 7) {
useHand = 'L';
} else if (n === 3 || n === 6 || n === 9) {
useHand = 'R';
} else {
const leftDiff = getDiff(leftPosition, n);
const rightDiff = getDiff(rightPosition, n);
if (leftDiff === rightDiff) {
useHand = hand === 'left' ? 'L' : 'R';
} else {
useHand = leftDiff < rightDiff ? 'L' : 'R';
}
}
leftPosition = useHand === 'L' ? n : leftPosition;
rightPosition = useHand === 'R' ? n : rightPosition;
result += useHand;
});
return result;
}