Skip to content

Instantly share code, notes, and snippets.

@mngatewood
Created January 28, 2019 16:58
Show Gist options
  • Save mngatewood/fb378845176e82b64ab10f977b2d5b0c to your computer and use it in GitHub Desktop.
Save mngatewood/fb378845176e82b64ab10f977b2d5b0c to your computer and use it in GitHub Desktop.
Robot Traversal
const returnsToOrigin = (commandString) => {
let heading = 'n';
let distanceX = 0;
let distanceY = 0;
const adjustDistance = (command) => {
if (command ==='g') {
if (heading === 'n') { distanceY++ }
else if (heading ==='e') { distanceX++ }
else if (heading ==='s') { distanceY-- }
else if (heading ==='w') { distanceX-- }
}
else if (command ==='r') {
if (heading === 'n') { heading = 'e' }
else if (heading ==='e') { heading = 's' }
else if (heading ==='s') { heading = 'w' }
else if (heading ==='w') { heading = 'n' }
}
else if (command ==='l') {
if (heading === 'n') { heading = 'w' }
else if (heading ==='e') { heading = 'n' }
else if (heading ==='s') { heading = 'e' }
else if (heading ==='w') { heading = 's' }
}
}
const batchCommands = (commandString) => {
const commandArray = commandString.toLowerCase().split('');
commandArray.forEach( command => {
adjustDistance(command)
});
}
batchCommands(commandString)
return distanceX === 0 && distanceY === 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment