Created
February 10, 2020 03:28
-
-
Save Sivakumar00/1fcb07dfcb27ba010db8ba5d3d56f8a8 to your computer and use it in GitHub Desktop.
Track the Robot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = [20, 30, 10, 40]; | |
const directions = { | |
NORTH: "NORTH", | |
EAST: "EAST", | |
WEST: "WEST", | |
SOUTH: "SOUTH" | |
}; | |
let currentDirection = directions.EAST; | |
let currentCoOrdinates = { | |
x: 0, | |
y: 0 | |
}; | |
const getFinalPosition = () => { | |
path.forEach(point => { | |
moveTo(point); | |
}); | |
console.log(JSON.stringify(currentCoOrdinates)); | |
console.log(currentDirection); | |
}; | |
const moveTo = point => { | |
if (currentDirection === directions.NORTH) { | |
currentCoOrdinates.y = currentCoOrdinates.y + point; | |
currentDirection = directions.EAST; | |
} else if (currentDirection === directions.EAST) { | |
currentCoOrdinates.x = currentCoOrdinates.x + point; | |
currentDirection = directions.SOUTH; | |
} else if (currentDirection === directions.SOUTH) { | |
currentCoOrdinates.y = currentCoOrdinates.y - point; | |
currentDirection = directions.WEST; | |
} else { | |
currentCoOrdinates.x = currentCoOrdinates.x - point; | |
currentDirection = directions.NORTH; | |
} | |
}; | |
getFinalPosition(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This robot roams around a 2D grid. It starts at (0, 0) facing North. After each time it moves, the robot rotates 90 degrees clockwise. Given the amount the robot has moved each time, you have to calculate the robot's final position. | |
To illustrate, if the robot is given the movements 20, 30, 10, 40 then it will move: | |
20 steps North, now at (0, 20) | |
30 steps East, now at (30, 20) | |
10 steps South. now at (30, 10) | |
40 steps West, now at (-10, 10) | |
...and will end up at coordinates (-10, 10). | |
--------------------------------------------------- | |
Examples | |
trackRobot(20, 30, 10, 40) ➞ [-10, 10] | |
trackRobot() ➞ [0, 0] | |
// No movement means the robot stays at (0, 0). | |
trackRobot(-10, 20, 10) ➞ [20, -20] | |
// The amount to move can be negative. | |
---------------------------------------------------- | |
Notes | |
Each movement is an integer (whole number). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment