Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If an int is 0 for north, 1 for east, etc... How do I reverse direction?

Tags:

java

I'm creating a program, and I need to keep track of which direction an object is facing. (north, east, south, west)

I'm not sure if this is even the best way to do that, so correct me on that if necessary, please.

In some instances, I'll need to turn left or right, and even reverse direction. What is the easiest way to achieve that?

This is in Java, and I can't use anything that is imported.

like image 749
KaiserCoaster Avatar asked Dec 12 '22 21:12

KaiserCoaster


2 Answers

Assuming the numbers are as such:

0 - North | 1 - East | 2 - South | 3 - West

Then running it through the algorithm

int reverse = (direction + 2) % 4;

should yield the reverse direction.

Let's test it:

North: 0 + 2 = 2. 2 % 4 = 2: South

South: 2 + 2 = 4. 4 % 4 = 0: North

East: 1 + 2 = 3. 3 % 4 = 3: West

West: 3 + 2 = 5. 5 % 4 = 1: East

Success!

Turning left and right is as simple as adding or subtracting, then taking the modulus of 4 to make sure it loops back around.

int left = (direction +3) % 4;
int right = (direction + 1) % 4;
like image 126
Logan Nichols Avatar answered Dec 29 '22 01:12

Logan Nichols


Using an enum type with values NORTH, EAST, SOUTH, WEST:

If

NORTH=0
EAST=1
SOUTH=2
WEST=3

Turning right is

(dir + 1) % 4

Turning left is

(dir + 3) % 4

Reversing direction is

(dir + 2) % 4

Note: In general, when you want to be able to add to integers and have them wrap around (2, 3, 0, 1, 2, 3, 0, ...) you need to use the modulo operator (%).

like image 33
chm Avatar answered Dec 29 '22 01:12

chm