0

Is it possible to create an algorithm which will return an ordered list of vectors representing the main eight directions on a 2d map? I do not want to hardcode the values, nor use a huge if/then/else or case tree if possible.

Here are the vectors I need to calculate, in order:

0, -1
1, -1
1, 0
1, 1
0, 1
-1, 1
-1, 0
-1, -1

Based on the following diagram, I need to generate the vector at the top first, then iterate clockwise for the rest:

Diagram

(I have a two dimensional array - x and y values - for a total of eight character positions. Each character starts in the center. I want to be able to generate each vector, in order, as I loop through the characters and then add the vector's x and y components to the associated character's position so that each character moves outward from the center in their associated direction.)

Do you see a pattern in those numbers above? Is it possible to devise an algorithm which will generate these pairs in the correct order or am I stuck with hard-coding them?

4
  • 1
    What's wrong with a hard-coded array? It's probably the fastest method. It's not like you want to run a sine and cosine function every time. Commented Jul 10, 2017 at 23:52
  • You're right, it's probably faster, but it's still an interesting puzzle that I'd like to solve. Commented Jul 11, 2017 at 0:03
  • 1
    If Y pointed up then it seems easier and more straight-forward than a left-handed coordinate system.
    – Holmz
    Commented Jul 11, 2017 at 6:43
  • In short you want to create 8 vectors and insert a unique co-ordinate from the array? Like vector 1 will the element (0,-1) whereas vector 2 will have (1,-1)? Commented Jul 11, 2017 at 17:12

1 Answer 1

1

Here's a pseudocode algorithm for it:

for i = 0 to 7
    x = ROUND(COS(i*PI/4.0), 0)
    y = ROUND(SIN(i*PI/4.0), 0)
next i

The ROUND(n,d) function is the same as the Excel formula function.

Of course, using COS/SIN is terribly inefficient.

Also, you may need to fiddle with it if you want a specific order. (I think change the loop to for i = 4 to -3 step -1 to get the order that you listed).

2
  • Just for what I was looking. Thanks! Commented Jul 11, 2017 at 18:32
  • @MarkInTheDark You'd have to compare speed with if (!x) x=-y else if (!y) y=x else if (x==y) x=0 else y=0. Commented Jul 12, 2017 at 0:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.