Search code examples
javaarraysloopsrules

Looping through 2 different Arrays to evaluate a condition in Java


I am trying to create a logic in database that creates rules for certain fields and then creates a condition logic based on those rules in Java.

Example1:

List1 = [OR, AND]
List2 = [true, false, true]

for example in above I want to check if (true OR false AND true) by looping through arrays in java. I know that below code that i used is totally wrong for this requirement and is not evaluating to my required condition ie if(true OR false AND true).

Please Note, I want this code in Java only not scripting language.

boolean previousResult = false;
   for(int i=0;i<List1.size();i++) {
     for(int j=0; j<List2.size();j++){
        if(List1.get(i) == "OR"){
            if(true || false){
                previousResult = true;
            }
        }else{ 
            if(previousResult && true){
              previousResult = true;
             }
        }
    }
}

The array length will change but will follow a same pattern as below:

Example2:

List1 = [OR, AND, OR]
List2 = [true, false, true, false]

Example3:

List1 = [OR, AND, OR, AND]
List2 = [true, false, true, false, true]

Example4:

List1 = [OR, AND, OR, AND, OR]
List2 = [true, false, true, false, true, false]

Solution

  • You don't need to loop over two arrays, because you always expect you array with arguments to be one element longer than the array with operators:

    class Playground {
        static enum BinaryOp {
            OR,
            AND
        }
    
        private static boolean evaluate(BinaryOp[] ops, Boolean[] vals) {
            assert vals.length > 1;
            assert ops.length == vals.length - 1;
            boolean result = vals[0];
            for (int i = 0; i < ops.length; i++) {
                if (ops[i].equals(BinaryOp.OR)) {
                    result = result || vals[i + 1];
                } else {
                    result = result && vals[i + 1];
                }
            }
            return result;
        }
    
        public static void main(String[ ] args) {
            System.out.println(
                evaluate(
                    new BinaryOp[] {BinaryOp.OR}, 
                    new Boolean[] {false, true}));
            System.out.println(
                evaluate(
                    new BinaryOp[] {BinaryOp.AND}, 
                    new Boolean[] {false, true}));
            System.out.println(
                evaluate(
                    new BinaryOp[] {BinaryOp.AND, BinaryOp.OR}, 
                    new Boolean[] {false, true, false}));
        }
    }
    

    Output:

    true
    false
    false