I require a function dist( a, b ) // 0 ≤ a,b < 12 which returns the shortest (absolute ie +ve) distance ala clock arithmetic, using modulo 12.
So for example,
dist( 1, 2 )
= dist( 2, 1 )
= dist( 11, 0 )
= dist( 0, 11 )
= dist( 0.5, 11.5 )
= 1
EDIT: while this can easily be done with a bit of hacking around, I feel that there must be some intuitive solution, may be using fmod and modulo 6
Firstly, an optimal solution is nontrivial, it took a little thinking.
float distMod12(float a,float b)
{
float diff = fabs( b - a );
return ( diff < 6 ) ? diff : 12 - diff;
}
EDIT: Alternatively,
return MIN( diff, 12 - diff ); // needs a MIN function
Complete code listing here: http://ideone.com/XxRIw
If I read that correctly, a and b aren't negative, and they are smaller than 12.
#include <math.h>
#include <stdio.h>
double min( double a, double b ) {
return a < b ? a : b;
}
double dist( double a, double b ) {
return min(
fmod( 12+b-a, 12 ),
fmod( 12+a-b, 12 )
);
}
int main() {
printf("%f\n", dist(1, 2));
printf("%f\n", dist(2, 1));
printf("%f\n", dist(11, 0));
printf("%f\n", dist(0, 11));
printf("%f\n", dist(0.5, 11.5));
return 0;
}
which simplifies to
double dist( double a, double b ) {
double diff = fmod( 12+a-b, 12 );
return diff <= 6 ? diff : 12-diff;
}
Something like
float dist( float a, float b ){
float amod, bmod;
amod = fmod( a, 12 );
bmod = fmod( b, 12 );
if( amod < bmod ) return dist( bmod, amod );
return min( amod-bmod, bmod-amod+12 );
}
Using the math library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With