<문제>
<나의 풀이>
function solution(numbers, hand) {
var answer = '';
let numbersIndex = {
1 : [0,0],
2 : [0,1],
3 : [0,2],
4 : [1,0],
5 : [1,1],
6 : [1,2],
7 : [2,0],
8 : [2,1],
9 : [2,2],
0 : [3,1],
"*" : [3,0],
"#" : [3,2],
};
let left = [1,4,7]
let right = [3,6,9]
let leftHand = "*";
let rightHand = "#";
for(let i = 0; i < numbers.length; i++) {
if(left.includes(numbers[i])) {
answer += "L"
leftHand = numbers[i]
}
else if (right.includes(numbers[i])) {
answer += "R"
rightHand = numbers[i]
}
else {
let r = numbersIndex[rightHand]
let l = numbersIndex[leftHand]
let c = numbersIndex[numbers[i]]
let rDistance = Math.abs(c[0] - r[0]) + Math.abs(c[1] - r[1])
let lDistance = Math.abs(c[0] - l[0]) + Math.abs(c[1] - l[1])
if(rDistance > lDistance) {
answer += "L";
leftHand = numbers[i]
}
else if(rDistance < lDistance) {
answer += "R";
rightHand = numbers[i]
}
else {
if(hand === "right") {
answer += "R";
rightHand = numbers[i]
}
else {
answer += "L";
leftHand = numbers[i]
}
}
}
}
return answer;
}
<다른 사람의 풀이>
function solution(numbers, hand) {
hand = hand[0] === "r" ? "R" : "L"
let position = [1, 4, 4, 4, 3, 3, 3, 2, 2, 2]
let h = { L: [1, 1], R: [1, 1] }
return numbers.map(x => {
if (/[147]/.test(x)) {
h.L = [position[x], 1]
return "L"
}
if (/[369]/.test(x)) {
h.R = [position[x], 1]
return "R"
}
let distL = Math.abs(position[x] - h.L[0]) + h.L[1]
let distR = Math.abs(position[x] - h.R[0]) + h.R[1]
if (distL === distR) {
h[hand] = [position[x], 0]
return hand
}
if (distL < distR) {
h.L = [position[x], 0]
return "L"
}
h.R = [position[x], 0]
return "R"
}).join("")
}