프로그래머스
https://programmers.co.kr/learn/courses/30/lessons/67256
나의 풀이
- 1,4,7은 현재 손가락의 위치가 어디든 왼손으로 누르고 3,6,9는 오른손으로 누르면 된다.
 
- 2,5,8,0의 경우 현재 손가락 위치에서 누르려는 숫자와 가까운 손가락으로 눌러야한다.
 
- 따라서 현재 왼쪽과 오른쪽 손가락 위치를 업데이트하면서 2,5,8,0 중 하나를 눌러야할때 왼쪽 손가락과 오른쪽 손가락, 그리고 누르려는 숫자의 좌표를 구한 뒤(findIdx 함수) 결과 좌표값을 토대로 거리를 각각 계산한다. (왼손에서 숫자까지, 오른손에서 숫자까지)
 
- 거리를 비교해 더 작은 값의 손가락을 리턴한다.
 
- 거리가 똑같다면 매개변수로 주어진 hand를 리턴한다.
 
function solution(numbers, hand){
  const keypad = [
        [1,2,3],
        [4,5,6],
        [7,8,9],
        ["*",0,"#"]
  ];
  let nowLeft = "*"; 
  let nowRight = "#"; 
  let res = ""; 
  
  
  const findIdx = (idx, num) => {
    for(let i=0;i<keypad.length;i++){
      if(keypad[i].includes(num)){
        idx.push(i, keypad[i].indexOf(num));
        return idx;
      }
    }
  }
  
  
  const calcDistance = (leftArr, rightArr, nextNum, hand) => {
    const nextNumIdx = findIdx([],nextNum);
    const path1 = Math.abs(leftArr[0]-nextNumIdx[0]) + Math.abs(rightArr[1]-nextNumIdx[1]); 
    const path2 = Math.abs(rightArr[0]-nextNumIdx[0]) + Math.abs(rightArr[1]-nextNumIdx[1]); 
    if(path1>path2){ 
      nowRight = nextNum;
      return "R";
    }
    else if(path1<path2){ 
      nowLeft = nextNum;
      return "L";
    }else{
      return `${hand}`;
    }
  }
  
  for(let i=0;i<numbers.length;i++){
    if([1,4,7].includes(numbers[i])){
      nowLeft = numbers[i];
      res += "L";
    }
    else if([3,6,9].includes(numbers[i])){
      nowRight = numbers[i];
      res += "R";
    }else{
      const leftIdx = findIdx([], nowLeft);
      const rightIdx = findIdx([], nowRight);
      const output = calcDistance(leftIdx, rightIdx, numbers[i], hand);
      
      if(output === "L" || output === "left"){
        nowLeft = numbers[i];
        res += "L";
      }else{
        nowRight = numbers[i];
        res += "R";
      }
    }
  }
  return res;
}