Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check value without control structure

Tags:

java

math

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?

like image 850
UserXY Avatar asked Nov 27 '22 08:11

UserXY


2 Answers

// 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.

like image 77
John Kugelman Avatar answered Dec 25 '22 21:12

John Kugelman


(value-1)-((value-1+31)%31)

0 means true, anything else means false.

like image 37
thejh Avatar answered Dec 25 '22 21:12

thejh