I'm trying to solve a problem I've got on my homework.
How can I check if a value is within a range, e.g. 1 ≤ value ≤ 31, without using if, switch, or any other control structure, in Java?
// Zero if valid, non-zero otherwise
int n = (int) Math.floor((value - 1) / 31.0);
// Convert any non-zero value to -1 (0xFFFFFFFF) without any boolean logic.
n |= n << 1; n |= n >> 1;
n |= n << 2; n |= n >> 2;
n |= n << 4; n |= n >> 4;
n |= n << 8; n |= n >> 8;
n |= n << 16; n |= n >> 16;
// Value is either -1 or 0. Switch -1 to +1.
n = -n;
// Use array indexing to simulate a conditional.
String[] results = {"valid", "invalid"};
System.out.println(results[n]);
See it run at http://ideone.com/98sA8.
You could even extend this to run different code paths:
Runnable[] options = {
new Runnable() {
public void run() {
System.out.println("valid");
}
},
new Runnable() {
public void run() {
System.out.println("invalid");
}
}
};
options[n].run();
See it run at http://ideone.com/sUKiW.
(value-1)-((value-1+31)%31)
0 means true, anything else means false.
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