๋ฌธ์ œ

์ˆœ์„œ๋Œ€๋กœ ๋ˆ„๋ฅผ ๋ฒˆํ˜ธ๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด numbers

์™ผ์†์žก์ด์ธ์ง€ ์˜ค๋ฅธ์†์žก์ด์ธ์ง€๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๋ฌธ์ž์—ด hand

→ ๊ฐ ๋ฒˆํ˜ธ๋ฅผ ๋ˆ„๋ฅธ ์—„์ง€์†๊ฐ€๋ฝ์ด ์™ผ์†์ธ์ง€ ์˜ค๋ฅธ์†์ธ์ง€๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์—ฐ์†๋œ ๋ฌธ์ž์—ด ํ˜•ํƒœ๋กœ return

 

 

์ฝ”๋“œ

const solution = (numbers, hand) => {
  let answer = '';

  let keypad = {
    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],
    '*': [3, 0],
    0: [3, 1],
    '#': [3, 2],
  };

  let leftHand = keypad['*'];
  let rightHand = keypad['#'];

  for (let x of numbers) {
    let [i, j] = keypad[x];

    if (j === 0) {
      answer += 'L';
      leftHand = keypad[x];
    }
    else if (j === 2) {
      answer += 'R';
      rightHand = keypad[x];
    }
    else {
      // ์™ผ์ชฝ ์†๊ฐ€๋ฝ ์œ„์น˜์™€ ํ˜„์žฌ ์œ„์น˜์™€ ๋–จ์–ด์ง„ ๊ฑฐ๋ฆฌ๊ณ„์‚ฐ
      let leftDistance = Math.abs(i - leftHand[0]) + Math.abs(j - leftHand[1]);
      // ์˜ค๋ฅธ์ชฝ ์†๊ฐ€๋ฝ ์œ„์น˜์™€ ํ˜„์žฌ ์œ„์น˜์™€ ๋–จ์–ด์ง„ ๊ฑฐ๋ฆฌ๊ณ„์‚ฐ
      let rightDistance = Math.abs(i - rightHand[0]) + Math.abs(j - rightHand[1]);

      if (leftDistance > rightDistance) {
        rightHand = keypad[x];
        answer += 'R';
      }
      else if (leftDistance < rightDistance) {
        leftHand = keypad[x];
        answer += 'L';
      }
      else if (leftDistance === rightDistance) {
        if (hand === 'left') {
          leftHand = keypad[x];
          answer += 'L';
        } else {
          rightHand = keypad[x];
          answer += 'R';
        }
      }
    }
  }
  return answer;
}

+ Recent posts