[프로그래머스] 키패드 누르기 (자바스크립트/javascript/js)

2021. 6. 22. 16:49Front-end/알고리즘

728x90
반응형

문제 출처 : https://programmers.co.kr/learn/courses/30/lessons/67256 (2020 카카오 인턴십)

function solution(numbers, hand) {
  const answerArray = [];
  let leftLocation = [3, 0];
  let rightLocation = [3, 2];

  for (let i = 0; i < numbers.length; i++) {
    let location = [];
    if (numbers[i] === 1 || numbers[i] === 4 || numbers[i] === 7) {
      answerArray.push("L");
    } else if (numbers[i] === 3 || numbers[i] === 6 || numbers[i] === 9) {
      answerArray.push("R");
    } else {
      // 2,5,8,0일 때
      let goalRow;
      let goalCol;
      if (numbers[i] === 2) {
        goalRow = 0;
        goalCol = 1;
      } else if (numbers[i] === 5) {
        goalRow = 1;
        goalCol = 1;
      } else if (numbers[i] === 8) {
        goalRow = 2;
        goalCol = 1;
      } else if (numbers[i] === 0) {
        goalRow = 3;
        goalCol = 1;
      }
      const leftSpace =
        Math.abs(leftLocation[0] - goalRow) +
        Math.abs(leftLocation[1] - goalCol);
      const rightSpace =
        Math.abs(rightLocation[0] - goalRow) +
        Math.abs(rightLocation[1] - goalCol);

      if (leftSpace < rightSpace) {
        // 왼손이 움직여야하는 칸이 더 적으면
        answerArray.push("L");
      } else if (leftSpace > rightSpace) {
        // 오른손이 움직여야 하는 칸이 더 적으면
        answerArray.push("R");
      } else {
        // 둘이 같으면
        if (hand === "left") {
          answerArray.push("L");
        } else {
          answerArray.push("R");
        }
      }
    }
    switch (numbers[i]) {
      case 1:
        location = [0, 0];
        break;
      case 2:
        location = [0, 1];
        break;
      case 3:
        location = [0, 2];
        break;
      case 4:
        location = [1, 0];
        break;
      case 5:
        location = [1, 1];
        break;
      case 6:
        location = [1, 2];
        break;
      case 7:
        location = [2, 0];
        break;
      case 8:
        location = [2, 1];
        break;
      case 9:
        location = [2, 2];
        break;
      case 0:
        location = [3, 1];
        break;
    }
    if (answerArray[answerArray.length - 1] === "L") {
      leftLocation = location;
    } else if (answerArray[answerArray.length - 1] === "R") {
      rightLocation = location;
    }
  }
  const answer = answerArray.join("");
  return answer;
}
728x90
반응형