Search code examples
javamultidimensional-arraytruthtable

truth table in 2D arry


Below, you'll see how I am building my truth table.

    //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));}

    }
}

Do you know how can I store my array to have somethin like this :

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

** S ** will be stored after.

tks


Solution

  • If you interpret false as 0 and true as 1 all possible combinations can be generated using the binary numbers from 0 to number of all combinations minus 1. If you have x variables the number of possible combinations is 2^x. For example

    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
    

    Using above insights your code could be something like:

    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();
        }      
    }