Assuming you have a sequence like this: 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, etc. Basically a sequence consisting of N numbers, repeating over and over.
What is the simplest algorithm for finding the distance/difference between two numbers in this sequence? For example the distance from 5 to 7 is +2 and the distance from 0 to 6 is -2. For a more high level view what I have a looping/repeating sequence number, and I need to find out how much “before” or “after” a number is of another on the closest path (fewest number between them).
Assuming X>Y:
Examples for N = 7:
dist(7, 5) = min {7-5, 7-(7-5-1)} = min {2, 6} = 2
dist(6, 0) = min {6-0, 7-(6-0-1)} = min {6, 2} = 2
dist(5, 1) = min {5-1, 7-(5-1-1)} = min {4, 4} = 4
The last example points a small flaw in your distance definition: Is dist(5, 1) = 4 or dist(5, 1) = -4 ? I’ve changed your definition a little bit to avoid negative distances (so my algorithm calculates the absolute value of the distance). If you want to keep your definition then make the distance negative if and only if the first argument of the
minis greater than the second.