function solution(numbers, hand) {
let answer =''
let leftNum=10;
let rightNum=12;
const xy={}
for(var i=0;i<4;i++)
{
for(var j=0;j<3;j++){
xy[j+i*3+1]=[i,j]
console.log(i,j)
}
}
for(let number of numbers){
if(number==="*")
number=10;
if(number==="#")
number=12
if(number===0)
number=11
if(number === 3 || number === 6 || number === 9){
answer+="R";
rightNum=number;
continue;
}
if(number === 1 || number === 4 || number === 7){
answer+="L";
leftNum=number;
continue;
}
const leftGap=getDistance(xy,leftNum,number);
const rightGap=getDistance(xy,rightNum,number);
if(leftGap===rightGap){
if(hand==="right"){
answer+="R"
rightNum=number;
continue;
}
if(hand==="left"){
answer+="L"
leftNum=number;
continue;
}
}
if(leftGap>rightGap){
answer+="R"
rightNum=number;
continue;
}
if(leftGap<rightGap){
answer+="L"
leftNum=number;
continue;
}
}
return answer;
}
const getDistance = (xy,locatedNumber, target) => {
const nowPosition = xy[locatedNumber];
const targetPosition = xy[target];
return Math.abs(targetPosition[0] - nowPosition[0]) + Math.abs(targetPosition[1] - nowPosition[1]);
};
사실 모범답안을 보고 조금 고쳤다.
일일히 따져가면서 하기보다는 좌표로 보는게 더 쉽다 .