Skip to content

Instantly share code, notes, and snippets.

@IrhaAli
Created October 15, 2022 22:02
Show Gist options
  • Save IrhaAli/7de22afcc8637e3c679cb6b811f52c69 to your computer and use it in GitHub Desktop.
Save IrhaAli/7de22afcc8637e3c679cb6b811f52c69 to your computer and use it in GitHub Desktop.
Returns the final position of a taxicab w.r.t the initial position, given a list of directions.
/*I don't understand for console.log(blocksAway(["left", 1, "right", 1, "left", 1, "right", 1, "left", 1, "right", 1]));
it's supposed to return east: 3 when it's clearly east: -3 (ie. west: 3). This is all with the assumption that the driver starts at (0,0) facing north */
const blocksAway = function(directions) {
let finalPosition = [0,0];
let carFacing = 'N';
for (let i = 0; i < directions.length ; i += 2){
if (directions[i] === 'right'){
switch (carFacing){
case 'N':
finalPosition[0] += directions[i+1];
carFacing = 'E';
break;
case 'S':
finalPosition[0] -= directions[i+1];
carFacing = 'W';
break;
case 'W':
finalPosition[1] += directions[i+1];
carFacing = 'N';
break;
case 'E':
finalPosition[1] -= directions[i+1];
carFacing = 'S';
}
}else{
switch (carFacing){
case 'N':
finalPosition[0] -= directions[i+1];
carFacing = 'W';
break;
case 'S':
finalPosition[0] += directions[i+1];
carFacing = 'E';
break;
case 'W':
finalPosition[1] -= directions[i+1];
carFacing = 'S';
break;
case 'E':
finalPosition[1] += directions[i+1];
carFacing = 'N';
}
}
}
return {east: finalPosition[0], north: finalPosition[1]};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment