-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.js
50 lines (42 loc) · 1018 Bytes
/
solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function isRobotBack(moves) {
const modifiers = ["*", "!", "?"];
const commands = {
R: [0, 1, "L"],
L: [0, -1, "R"],
U: [1, 1, "D"],
D: [1, -1, "U"],
};
const done = [];
let modifier = null;
const position = [0, 0];
for (let i = 0; i < moves.length; i++) {
const mov = moves[i];
if (modifiers.includes(mov)) {
modifier = mov;
continue;
}
let command = mov;
if (modifier) {
if (modifier === "*") {
command = command.repeat(2);
}
if (modifier === "!") {
command = commands[mov][2];
}
if (modifier === "?") {
if (done.includes(command)) {
command = null;
}
}
modifier = null;
}
if (command) {
for (const movement of command) {
const [index, increment] = commands[movement];
position[index] = position[index] + increment;
}
done.push(command[0]);
}
}
return position[0] === 0 && position[1] === 0 ? true : position;
}