2D arry中的真值表

时间:2019-02-27 12:16:43

标签: java multidimensional-array truthtable

下面,您将看到我如何构建真值表。

    //Tab 2D represents truth table
    //tt [nbr of combinaisons] [nbr of variables + S]
    boolean tt [][] = new boolean [nbrCombinaisons][nbrVariables+1];
    for (int j = 0; j < nbrVariables; j++) {    
        for (int i = 0; i < nbrCombinaisons; i++) { 
            tt[i][j] = true;
        }
    }
    //Display truth tab in console
    for (boolean[] row : tt) { System.out.println(Arrays.toString(row));}

    }
}

您知道如何存储我的数组以具有类似这样的内容:

False False  **False**
False True   **False**
True  False  **False**
True  True   **False**

** S ** will be stored after.

tks

1 个答案:

答案 0 :(得分:0)

如果将false解释为0,将true解释为1,则可以使用从0到所有组合数减1的二进制数生成所有可能的组合。如果您有x个变量,则可能的组合数为2 ^ x。例如

for 2 variables count of combinations is 2^2 = 4 and the binary numbers from 0 to 4-1 are

00
01
10
11

for 3 variables count of combinations is 2^3 = 8 and the binary numbers from 0 to 8-1 are

000
001
010
011
100
101
110
111

利用以上见解,您的代码可能类似于:

public static void main(String[]args) {        
    int nbrVariables = 2;
    int nbrCombinaisons = (int) Math.pow(2, nbrVariables);

    boolean tt [][] = new boolean [nbrCombinaisons][nbrVariables+1];        
    for (int j = 0; j < nbrCombinaisons; j++) {             
        String    tempStr  = String.format("%"+nbrVariables+"s", Integer.toBinaryString(j)).replace(" ", "0");
        boolean[] tempBool = new boolean[tempStr.length()+1];
        boolean total = tempStr.charAt(0)=='1';
        for(int i=0; i<tempStr.length(); i++){
            tempBool[i]= tempStr.charAt(i)=='1';
            if(i>0){
                total = total && tempBool[i];  //table for logical AND change operator to || for OR or ^ for XOR
            }
        }
        tempBool[tempStr.length()] = total;
        tt[j] = tempBool;
    }

    for (boolean[] row : tt) {            
        for (boolean c : row) { 
            System.out.print(c + "\t");        
        }
        System.out.println();
    }      
}