Generating truth tables in Java

后端 未结 7 518
悲哀的现实
悲哀的现实 2021-01-02 16:42

I\'m trying to print some truth tables as part of a school assignment. How can I generate a dynamic size truth table in Java?

So that printTruthTable(1)

7条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-02 17:10

    I had to do something similar recently except the project was to generate a truth table for a given logical expression. This is what I came up with for assigning independent variables their truth values.

        column = 0;
    
        while (column < numVariables)
        {
            state = false;
            toggle = (short) Math.pow(2, numVariables - column - 1);
    
            row = 1;
            while (row < rows)
            {
                if ((row -1)%toggle == 0)
                    state = !state;
    
                if (state)
                    truthTable[row][column] = 'T';
                else
                    truthTable[row][column] = 'F';
    
                row++;
            }
    
            column++;
        }
    

    This is assuming your first row is populated with variable names and sub-expressions. The math might change slightly if you want to start with row 0.

    This bit....

    if ((row -1)%toggle == 0)

    would become....

    if (row%toggle == 0)

提交回复
热议问题