Modular Character Comparison

This seems like a very simple question, but nothing surprising has been written about it on the Internet, and it’s hard for me to do it correctly on my own. What is the best way to implement a modular comparison function for ASCII characters in Java, so that comparison wraps the end of the alphabet? I want to use it for an “between” function, which can split the entire alphabet into arbitrary locations and correctly return “true” when asked if “y” is between “x” and “b”.

I already found all the questions and answers that talk about modular arithmetic for characters, so I know how to do modular addition (moving characters) with this code:

char shifted = (((original - 'a') + 1) % 26) + 'a';

However, this is based on Java, built in modular arithmetic functions that have no equivalent for comparison. Even if I use simple ints, I cannot ask Java if a <b <c mod 26 (which should return true if a = 24, b = 25 and c = 1).

So, the general question: what is the best way to implement modular comparison operations in Java? If this is too complex a problem, is there at least one way to make such comparisons work for the ASCII alphabet?

+5
source share
3 answers

When testing A < B < Cin a circular queue, you can always accept A <= Band either wrapped or not.

If A < B, the wrap did not happen. If either B < C or C < A, then B is between A and C.

A > B, . B < C and C < A, B A C.

, A == B, B == C == C.

+2

, : c_1 c_2 c_3, , ?

  • (.. a = 1, b = 2,..., z = 26). c_1 = 'y' = 25 c_2 = 'x' = 24 c_3 = 'b' = 2).
  • c_3 < c_2, 26 c_3. , 2 < 24.
  • c_1 = 25, c_2 = 24 c_3 = 28.
  • , c_1 >= c_2 && c_1 <= c_3. , . , .
  • 26 c_1 , . , . , .

26 "" . :

... 23 24 25 26 1 2 3 4

:

... 23 24 25 26 27 28 29 30

, .

: , MvG. : "25 24 2?" "1 24 2?". , (1 + 26) 24 (2 + 26) - , "a" "x" "b".

+1

, . , :

public static boolean isStrictlyBetween(char a, char x, char b) {
    // assuming x, a, and b are all the same case (lower or upper).
    return ((x - a + 26) % 26) < ((b - a + 26) % 26);
}

This code says it returns true if the clockwise distance from a to x is less than the clockwise distance from a to b. +26 says that the result of the difference expression is positive (% of negative numbers work strange in some languages). % 26 executes your desired module.

0
source

All Articles