Sign preserving modular distance
This will embarrass me later, when I think of a better solution. But, sometimes, you need a fast and dirty answer.
I want a modulus operator Mod(a,b,m)
such that:
Mod(2,6,7)=-3
Mod(6,2,7)=3
That is, the operator avoids the 4-hop path between 2 and 6 and, instead,
circles around via a path of length 3. The answer preserves the path direction
if you leave from a
and go to b
.
The following code calculates this. There's got to be a better way.
#include <iostream>
#include <cmath>
double absmin(double a, double b){
if(std::abs(a)<std::abs(b))
return a;
else
return b;
}
double ModDist(double src, double dest, double m){
if(dest<src)
return absmin(dest+m-src, dest-src);
else
return absmin(dest-src, dest-m-src);
}
int main(){
std::cout<<ModDist(2,6,7)<<std::endl;
std::cout<<ModDist(6,2,7)<<std::endl;
}