0
votes

given is a Cartesian coordinate system and a point(x,y) within this system. For example a point p has the coordinates (-12,2):

                  |
                  |
      p           |
                  |
------------------+------------------>
                  |
                  |
                  |
                  |

Now I need a function/algorithm that calculates the opposite "direction" (north, east, south, west) from the coordinate system's center (0,0) based on the given point. In our example the best opposite direction to choose would be EAST, following the X-axis to the right.

However, in some situations within my application not all directions are an option to choose, in such a case the next-best direction has to be chosen. In our example, if EAST would not be possible, then the next-best direction would be SOUTH (then NORTH, then WEST).

I could solve this with some if-statements, but that does not seem to be very elegant.
Any other (better) ideas?

2

2 Answers

3
votes

Use the dot product of your vector (x, y) with the unit vectors along the four directions

(1, 0), (-1, 0), (0, 1), (0, -1).

The smallest number corresponds the direction you want. Then the second smallest, and so on.

This works for any directions not just E, W, S and N - you just need to pick unit vectors along the desired directions and compare the dot products

2
votes

The 'true' opposite direction is -P i.e. (12,-2)

The "best" direction is the longer magnitude, i.e. (12,0). You normalize it and get (1,0) which is east.

The next best direction is the shorter magnitude, i.e. (0,-2). You normalize it and get (0,-1) which is south.

In general, if you are constrained to go along a certain set of unit vectors, you use the one with the maximal dot product.