Skip to content

Commit 156e10e

Browse files
committed
Keypad press / 심화
1 parent 1cd3d4b commit 156e10e

File tree

1 file changed

+119
-0
lines changed

1 file changed

+119
-0
lines changed
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
// 방법 1: 객체기반 접근(각 숫자의 좌표 직접 매핑 - 하드코딩)
2+
function solution1(numbers, hand) {
3+
const keypad = {
4+
1: [0, 0],
5+
2: [0, 1],
6+
3: [0, 2],
7+
4: [1, 0],
8+
5: [1, 1],
9+
6: [1, 2],
10+
7: [2, 0],
11+
8: [2, 1],
12+
9: [2, 2],
13+
"*": [3, 0],
14+
0: [3, 1],
15+
"#": [3, 2],
16+
}
17+
18+
let left = keypad["*"]
19+
let right = keypad["#"]
20+
21+
const getDist = ([y1, x1], [y2, x2]) => Math.abs(y1 - y2) + Math.abs(x1 - x2)
22+
23+
return numbers
24+
.map((num) => {
25+
const target = keypad[num]
26+
27+
// 왼쪽 열이면, 왼손
28+
if (target[1] === 0) {
29+
left = target
30+
return "L"
31+
}
32+
// 오른쪽 열이면, 오른손
33+
if (target[1] === 2) {
34+
right = target
35+
return "R"
36+
}
37+
38+
// 가운데열의 경우, 거리 비교
39+
const leftDist = getDist(left, target)
40+
const rightDist = getDist(right, target)
41+
42+
if (leftDist === rightDist) {
43+
if (hand === "right") {
44+
right = target
45+
return "R"
46+
}
47+
left = target
48+
return "L"
49+
}
50+
51+
if (leftDist < rightDist) {
52+
left = target
53+
return "L"
54+
} else {
55+
right = target
56+
return "R"
57+
}
58+
})
59+
.join("")
60+
}
61+
62+
// 방법 2: 2차원 배열로 실제 키패드 모양 표현 후, 좌표 매핑
63+
function solution2(numbers, hand) {
64+
// 키패드를 2차원 배열로 정의
65+
const keypad = [
66+
[1, 2, 3],
67+
[4, 5, 6],
68+
[7, 8, 9],
69+
["*", 0, "#"],
70+
]
71+
72+
// 키패드를 좌표로 매핑
73+
const getPos = new Map(
74+
keypad.flatMap((row, y) => row.map((num, x) => [num, [y, x]]))
75+
)
76+
77+
let left = getPos.get("*")
78+
let right = getPos.get("#")
79+
80+
const getDist = ([y1, x1], [y2, x2]) => Math.abs(y1 - y2) + Math.abs(x1 - x2)
81+
82+
return numbers
83+
.map((num) => {
84+
const target = getPos.get(num)
85+
86+
// 왼쪽 열이면, 왼손
87+
if (target[1] === 0) {
88+
left = target
89+
return "L"
90+
}
91+
// 오른쪽 열이면, 오른손
92+
if (target[1] === 2) {
93+
right = target
94+
return "R"
95+
}
96+
97+
// 가운데 열
98+
const leftDist = getDist(left, target)
99+
const rightDist = getDist(right, target)
100+
101+
if (leftDist === rightDist) {
102+
if (hand === "right") {
103+
right = target
104+
return "R"
105+
}
106+
left = target
107+
return "L"
108+
}
109+
110+
if (leftDist < rightDist) {
111+
left = target
112+
return "L"
113+
} else {
114+
right = target
115+
return "R"
116+
}
117+
})
118+
.join("")
119+
}

0 commit comments

Comments
 (0)