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

Suppose we have a numbered circle. We want to move from point A to point B, but we do not know whether we should go left or right. How would you use numbers to figure out which direction you should go?

Example:

Now we are at 1. We want to continue 5. I see vissualy that 5 is closer, so we go right. Also note that you are always facing inward.

img

+5
source share
6 answers

, , , 6 ( n). -2 6 = 4. . - B-A, A-B. , .

:

A = 1, B = 5

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

2:

A = 5, B = 1

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

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

. ( 6 1), , !

+2

( ). ABS .

a,b | x1 = abs(b-a) < max/2 | x2 = b-a > 0 | x1 == x2 
2,3 | true                  | true         | true
1,6 | false                 | true         | false
6,1 | false                 | false        | true
5,4 | true                  | false        | false

= (x1 = abs (b-a) < max/2) == (x2 = b-a > 0)

+1

scala . , , 3, , , :

def fromAtoBClockwise (a: Int, b: Int) : Boolean = { 
  if (a > b) ! fromAtoBClockwise (b, a)
  else b - a  <= 3 }

3, 1 - 5, , a > b.

def fromAtoBClockwise (a: Int, b: Int) : Boolean = { 
  if (a > b) fromAtoBClockwise (a, b + 6)
  else b - a  <= 3 } 

- 6, , b, .

, , .

:

def fromAtoBClockwise (a: Int, b: Int, size: Int) : Boolean = { 
  if (a > b) ! fromAtoBClockwise (b, a, size)
  else b - a  <= size/2 } 


def fromAtoBClockwise (a: Int, b: Int, size: Int) : Boolean = { 
  if (a > b) fromAtoBClockwise (a, b + size, size)
  else b - a  <= size/2 } 

( ):

(1 to 5).map (a => (1 to 5).map (b => { if (a != b) println (a + " " + b + " " + fromAtoBClockwise (a, b, 5))}))

1 2 true    1 3 true    1 4 false   1 5 false
2 1 false   2 3 true    2 4 true    2 5 false
3 1 false   3 2 false   3 4 true    3 5 true
4 1 true    4 2 false   4 3 false   4 5 true
5 1 true    5 2 true    5 3 false   5 4 false
+1

a == , b ==

pointAtoPointB = 0

for a to b
  pointAtoPointB ++

pointBtoPointA = 0

for b to a
  pointBtoPointA ++

if pointBtoPointA > pointAtoPointB
  go a to b
else
  go b to a 
0
clockWise = B - A <  A + MAX - B

B > A .

-1
source

All Articles