|
| 1 | +// Problem: The robot moves on an plane, and its movements are described by a command string consisting of one or more of the following letters. |
| 2 | +// - G instructs the robot to move forward one step |
| 3 | +// - L instructs the robot to turn left |
| 4 | +// - R instructs the robot to turn right |
| 5 | +// The robot cannot go backwards. After running all of the movement commands, check if robot returns to the starting location. |
| 6 | +// Time complexity: O(n) |
| 7 | + |
| 8 | +function checkRobotLocation(str) { |
| 9 | + const operation = str.split(""); |
| 10 | + let x = 0; |
| 11 | + let y = 0; |
| 12 | + let directions = ["N", "E", "S", "W"]; |
| 13 | + let direction = directions[0]; |
| 14 | + |
| 15 | + operation.forEach((task) => { |
| 16 | + if (task === "G") { |
| 17 | + direction === "N" && (y += 1); |
| 18 | + direction === "S" && (y -= 1); |
| 19 | + direction === "E" && (x += 1); |
| 20 | + direction === "W" && (x -= 1); |
| 21 | + } else if (task === "R") { |
| 22 | + let i = directions.indexOf(direction); |
| 23 | + directions.length <= i + 1 |
| 24 | + ? (direction = directions[0]) |
| 25 | + : (direction = directions[i + 1]); |
| 26 | + } else if (task === "L") { |
| 27 | + let i = directions.indexOf(direction); |
| 28 | + i > 0 |
| 29 | + ? (direction = directions[i - 1]) |
| 30 | + : (direction = directions[directions.length - 1]); |
| 31 | + } |
| 32 | + }); |
| 33 | + return x === 0 && y === 0 ? true : false; |
| 34 | +} |
| 35 | + |
| 36 | +export default checkRobotLocation; |
0 commit comments