Java permutation and union of boolean flags

I have some boolean variables that will be passed as arguments

boolean var1; boolean var2; boolean var3; boolean var4; 

Depending on these variables, I have to encode something like this

 if (var1 && !var2 && !var3 && !var4) { //do something } elsif (var1 && var2 && !var3 && !var4) { //do something } 

. ,, etc., using all possible combinations. I can do this using the if-else statement. You need to know if there is another approach. Thanks in advance.

+5
source share
4 answers

Create a bit pattern from four logical arguments, for example. 0110 means var1 = false , var2 = true , var3 = true and var4 = false .

Then you can use the switch construct for the generated numbers.

 int b = (var1 ? 8 : 0) | (var2 ? 4 : 0) | (var3 ? 2 : 0) | (var4 ? 1 : 0); switch(b) { case 0: ... case 1: ... } 
+3
source

I do not think there is a better approach. It depends on your codes. If you really need the codes 2 * 2 * 2 * 2 codes, you will need to write this code somewhere. Either you create a large if-else block, as you suggest, or find another way to specify an implementation based on your flags (strategy template, switch, ..).

+1
source

The algorithm has 2 steps:

Step 1 Create N! permutation cases

Step 2 In the specific case, using the De Morgan theorem :

 VAR_1 && !VAR_2 && !VAR_3 && ... && !VAR_N = VAR_1 AND !OR(VAR_2, VAR_3, ... VAR_N) 

similarly, we have another case:

 AND(VAR_1, VAR_2) AND !OR(VAR_3, VAR_4, ..., VAR_N) AND(VAR_1, VAR_2, VAR_3) AND !OR(VAR_4, VAR5, ..., VAR_N) ... AND(VAR_1, ..., VAR_(N-1)) AND !OR(VAR_N) 
0
source

You cannot reduce the number of conditions, but you can simplify such conditions using Arrays.equals :

 boolean var1; boolean var2; boolean var3; boolean var4; boolean[] varArr = new boolean[]{var1, var2, var3, var4}; if (Arrays.equals(varArr, new boolean[]{false, false, false, false})) { // handle case1 } else if (Arrays.equals(varArr, new boolean[]{true, false, false, false})) { // handle case2 } else if (Arrays.equals(varArr, new boolean[]{true, true, false, false})) { // handle case3 } ... ... 
0
source

Source: https://habr.com/ru/post/1210169/


All Articles