-
Notifications
You must be signed in to change notification settings - Fork 225
/
1041-robot-bounded-in-circle.js
59 lines (55 loc) · 1.34 KB
/
1041-robot-bounded-in-circle.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
50
51
52
53
54
55
56
57
58
59
/**
* @param {string} instructions
* @return {boolean}
*/
const isRobotBounded = function(instructions) {
let x = 0, y = 0, i = 0, d = [[0, 1], [1, 0], [0, -1], [ -1, 0]];
for (let j = 0; j < instructions.length; ++j)
if (instructions.charAt(j) === 'R') i = (i + 1) % 4;
else if (instructions .charAt(j) === 'L') i = (i + 3) % 4;
else {
x += d[i][0]; y += d[i][1];
}
return x == 0 && y == 0 || i > 0;
};
// another
/**
* @param {string} instructions
* @return {boolean}
*/
const isRobotBounded = function(instructions) {
let x = 0, y = 0, i = 0
const dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]] // U, R, D, L
for(let e of instructions) {
if(e === 'R') {
i = (i + 1) % 4
} else if(e === 'L') {
i = (i + 3) % 4
} else {
x += dirs[i][0]
y += dirs[i][1]
}
}
return x === 0 && y === 0 || i > 0
};
// another
/**
* @param {string} instructions
* @return {boolean}
*/
const isRobotBounded = function(instructions) {
const dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]]
let x = 0, y = 0, i = 0
for(let ins of instructions) {
if(ins === 'G') {
const dir = dirs[i]
x += dir[0]
y += dir[1]
} else if(ins === 'L') {
i = i - 1 < 0 ? 3 : i - 1
} else if(ins === 'R') {
i = i + 1 > 3 ? 0 : i + 1
}
}
return x === 0 && y === 0 || i !== 0
};