【问题标题】:truth table in 2D arry二维数组中的真值表
【发布时间】:2019-07-21 03:57:54
【问题描述】:

下面,你会看到我是如何构建我的真值表的。

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

【问题讨论】:

  • 我不确定我是否理解您的要求。您显示的输出看起来像一个 4x3 2d 数组(4 行 3 列) - 问题出在哪里?
  • 好的,从任何布尔表达式,我想创建他的真值表。这就是我使用二维数组的原因。如果在我的表达式中我只有 2 个变量 (a - b),那么我有 4 个组合(4 行和 3 列[a,b 和我的输出])。但我不知道如何将所有组合存储在我的表中......关于我的输出,目前,我不在乎,我会在之后做。我希望被更多人理解。谢谢
  • 仍然不清楚,您已经将所有组合存储在 boolean[][] 中,其中包含变量和输出的所有列。你的问题是如何填充矩阵,即如何生成所有的组合?
  • 是的,这是我的问题
  • 也许您应该编辑问题以包含该问题(生成矩阵)。简单的解决方案tt[0][0] = false; tt[0][1] = false; tt[1][0]= ... 或使用循环和一些位逻辑(提示:for (var i=0; i&lt;4; i++) System.out.println(((i&amp;2)!=0) + " " + ((i&amp;1)!=0));

标签: java multidimensional-array truthtable


【解决方案1】:

如果您将 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();
    }      
}

【讨论】:

    猜你喜欢
    • 2021-04-20
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2014-03-08
    • 2015-06-16
    • 2016-09-19
    • 2017-01-19
    • 2011-06-26
    相关资源
    最近更新 更多