简体   繁体   中英

Find all possible combinations in a boolean expression tree in java

I was trying to find all possible combination of expressions in a given condition.

For example, consider the following condition.

((b > 5) | (c > 4)) & ((c < 6) | (b < 2))) 

I need the final combination like

[(b > 5) , (c < 6)]
[(b > 5) , (b < 2)]
[(c > 4) , (c < 6)]
[(c > 4) , (b < 2)]

The logic is just like (a|b)&(c|d) -> a&c,a&d,b&c,b&d . The comma (,) above can be considered as an AND operator.

Since a tree is the best solution to parse expressions, I managed to build an Abstract Syntax Tree using a Recursive Descent Parser using java with the tree looking like the following.

布尔表达式树

I use a modified version of parser as described in this blog. This is where I am stuck as I don't how to extract the final expressions.

Is there any inputs to which direction I could try.

Other examples consider the following condition.

((b > 5) & ((c < 6) | (b < 2))) 

Result:

[(b > 5) , (c < 6)]
[(b > 5) , (b < 2)]

consider the following condition.

((b > 5) | ((c < 6) & (b < 2))) 

Result:

[(b > 5)]
[(c < 6) , (b < 2)]

No need for a tree here. You can begin by making a 2D matrix of the conditions. so for

        (b > 5) | (c > 4)) & ((c < 6) | (b < 2)))

The matrix would be 2X2 and look like:

(b > 5) (c > 4)
(c < 6) (b < 2)

In any row the condition between the neighbors would be OR and in any column the condition between neighbors would be AND. Now all you have to do generate all possible combinations of this 2D matrix. For that you can follow How to get 2D array possible combinations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM