-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0874-walking-robot-simulation.js
More file actions
64 lines (58 loc) · 1.75 KB
/
0874-walking-robot-simulation.js
File metadata and controls
64 lines (58 loc) · 1.75 KB
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
60
61
62
63
64
/**
* Walking Robot Simulation
* Time Complexity: O(M + N * K)
* Space Complexity: O(M)
*/
var robotSim = function (inputCommands, gridObstacles) {
const cardinalDirections = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0],
];
const blockedLocationsSet = new Set(
gridObstacles.map(([obstacleX, obstacleY]) => `${obstacleX},${obstacleY}`),
);
let currentRobotX = 0;
let currentRobotY = 0;
let robotHeadingIndex = 0;
let maxEuclideanDistanceSquared = 0;
for (
let instructionPointer = 0;
instructionPointer < inputCommands.length;
instructionPointer++
) {
const currentInstruction = inputCommands[instructionPointer];
switch (currentInstruction) {
case -1:
robotHeadingIndex = (robotHeadingIndex + 1) % 4;
break;
case -2:
robotHeadingIndex = (robotHeadingIndex + 3) % 4;
break;
default:
const [deltaMoveX, deltaMoveY] = cardinalDirections[robotHeadingIndex];
let unitsAdvanced = 0;
let obstacleWasHit = false;
while (unitsAdvanced < currentInstruction && !obstacleWasHit) {
const nextProspectiveX = currentRobotX + deltaMoveX;
const nextProspectiveY = currentRobotY + deltaMoveY;
if (
blockedLocationsSet.has(`${nextProspectiveX},${nextProspectiveY}`)
) {
obstacleWasHit = true;
} else {
currentRobotX = nextProspectiveX;
currentRobotY = nextProspectiveY;
maxEuclideanDistanceSquared = Math.max(
maxEuclideanDistanceSquared,
currentRobotX * currentRobotX + currentRobotY * currentRobotY,
);
}
unitsAdvanced++;
}
break;
}
}
return maxEuclideanDistanceSquared;
};