Created
December 16, 2018 21:58
-
-
Save shsunmoonlee/5ea37e9cc6800ca2762e9d6196e73fee to your computer and use it in GitHub Desktop.
mars rover controller
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
| // We have a space exploration vehicle called “Creativity” that was sent to Mars some time ago. We can drive it from Earth by sending a planned route to the vehicle. Route is a sequence of characters, each of which changes the position of the vehicle by at most one coordinate on a two-dimensional grid. Given the route, we want to know how many times the vehicle crosses the starting point of the trip. | |
| // Write a function ‘check(route)’ that returns the number of times the vehicle was in the starting point. ‘route’ is a string parameter composed of characters ‘W’, ‘A’, ‘S’, ‘D’, ‘Q’, ‘Z’, ‘E’, ‘C’. Each character defines a move, as described belo | |
| const orders = { | |
| W: (x,y) => ({x, y: y+1}), | |
| A: (x,y) => ({x: x-1,y}), | |
| S: (x,y) => ({x,y: y-1}), | |
| D: (x,y) => ({x: x+1,y}), | |
| Q: (x,y) => ({x: x-1, y: y+1}), | |
| Z: (x,y) => ({x: x-1, y: y-1}), | |
| E: (x,y) => ({x: x+1, y: y+1}), | |
| C: (x,y) => ({x: x+1, y: y-1}) | |
| } | |
| function check(route) { | |
| let x=0 , y= 0, count =1 | |
| route.split('').map(direction => { | |
| console.log("x,y",x,y); | |
| ({x,y} = orders[direction](x,y)) | |
| if(x===0 && y===0) { | |
| count ++ | |
| } | |
| }) | |
| return count | |
| } | |
| check("WA") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment