Search code examples
algorithmmathcyclemodulus

Check if cyclic (modulo 16) number is larger than another?


I have two a cyclic integer, modulo 16, so they assume values between 0 and 15.

I need to compare two numbers to determine if n_1 is greater than n_0

n_1 > n_0

Obviously, this is not exactly defined, so I define n_1 to be greater than n_0 if it is less than 8 "numbers" ahead, otherwise, it is lesser than n_0 (if not equal).

I.e. if:

n_0 = 0
if n_1 is between 1 and 8 (both inclusive)
then n_1 is greater than n_0.

n_0 = 5
if n_1 is between 6 and 15 (both inclusive)
then n_1 is greater than n_0.

n_0 = 12
if n_1 is between 13 and 15 (both inclusive)
    or between 0 and 4 (both inclusive)
then n_1 is greater than n_0.

How do I express this comparison programatically?

I am sure I am confusing the terminology above, so please feel free to correct my wording. :)


Solution

  • I was thinking of a clock with 16 hours. The idea is basically to move n0 to the 0 position and move n1 the same amount of "ticks". Now you can simply check if n1 is greater or smaller dependent on if it is before 8 or after 8 o'clock.

    public int compare (int n0, int n1){
        int ticksToZero = 16 - n0;
        if(n0 == n1)
            return 0;
        else if((n1 + ticksToZero) % 16 <= 8)
            return -1; //n0 is smaller than n1
        else
            return 1; //n0 is larger than n1
    }