Search code examples
algorithmlogicdistancedirection

Simple, short, logical algorithm (which direction to go?)


Suppose we have a numbered circle. We want to go from point A to point B but we don't know if we should go to the left or to the right. How would you, using numbers, calculate in which direction you should go?

Example:

We are currently on 1. We want to go on 5. I can see vissualy that 5 is closer so we go to the right. Also note, that you are always facing inwards.

img


Solution

  • First make sure that every calculation you do is modulo 6 (or n). That means -2 modulo 6 = 4. Then you can calculate once a clockwise trip and one counter clockwise. The clockwise trip is B-A, counter clockwise A-B. Then compare those two results, the lower one wins.

    Example:

    A = 1, B = 5

    clockwise move: B-A = 4
    counter cw move: A-B = -4 = 2

    Example 2:

    A = 5, B = 1

    clockwise move: B-A = 2
    counter cw move: A-B = 4