Engo Engo - 7 days ago 6
C++ Question

How to compute distance between numbers in c++?l

I want to compute the distance between numbers with help of the system described in the attached image.

For example: distance between 7 and 5 is -2, distance between 7 and 1 is 2 etc...

Any ideas how to do this in c++? The prefered direction is counter clockwise...
I am using a (int) vector.

enter image description here

Answer

These are really complicated answers. Here is a simpler one:

int distance(int x, int y) {
    int d = (y - x) & 7;
    return d > 4 ? d - 8 : d;
}

This always returns a result in the range -3..+4. Modular arithmetic is a little simpler to write when the ring size is a power of two, as is the case here.

distance(7, 5) = -2
distance(5, 7) = +2
distance(6, 2) = +4
distance(2, 6) = +4
Comments