๋ฌธ์
์์๋๋ก ๋๋ฅผ ๋ฒํธ๊ฐ ๋ด๊ธด ๋ฐฐ์ด 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;
}
'๐กAlgorithm > ๋ฌธ์ ํ๊ธฐ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
JS์๊ณ ๋ฆฌ์ฆ | ํ๋ก๊ทธ๋๋จธ์ค(Level 1) - ์์๋ง๋ค๊ธฐ (0) | 2021.09.16 |
---|---|
JS์๊ณ ๋ฆฌ์ฆ | ํ๋ก๊ทธ๋๋จธ์ค(Level 1) - ํฌ๋ ์ธ ์ธํ๋ฝ๊ธฐ ๊ฒ์ (0) | 2021.09.15 |
JS์๊ณ ๋ฆฌ์ฆ | ํ๋ก๊ทธ๋๋จธ์ค(Level 1) - ์์ฐ (0) | 2021.09.14 |
JS์๊ณ ๋ฆฌ์ฆ | ํ๋ก๊ทธ๋๋จธ์ค(Level 1) - 3์ง๋ฒ ๋ค์ง๊ธฐ (0) | 2021.09.14 |
JS์๊ณ ๋ฆฌ์ฆ | ํ๋ก๊ทธ๋๋จธ์ค(Level 1) - ๋คํธ๊ฒ์ (0) | 2021.09.13 |