Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 224
c0dehunter Avatar asked Feb 08 '12 21:02

c0dehunter


2 Answers

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

like image 114
duedl0r Avatar answered Sep 25 '22 06:09

duedl0r


If B > A
  If B - A > max/2, head CCW, else CW
Else
  If A - B > max/2, head CW, else CCW

i.e. if not crossing the wrap-around point (from 6 to 1) is more than halfway around, cross the wrap-around point!

like image 36
ibiwan Avatar answered Sep 22 '22 06:09

ibiwan