Таблица истинности в 2D Arry - PullRequest
0 голосов
/ 27 февраля 2019

Ниже вы увидите, как я строю свою таблицу истинности.

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

ТКС

1 Ответ

0 голосов
/ 27 февраля 2019

Если вы интерпретируете 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();
    }      
}
...