Search code examples
javalogic

Creating truth tables for propositional logic formulas?


I wanted to create a program that, given a logic formula by the user, for example ((¬A ∧ B) ∨ C) ∧ A, calculates its truth table. In this case the formula would be true if A=1, B=0, C=1, or if A=1, B=1, C=1, and it would be false in any other case.

But, I don't know how to create a method that can read the expression given, and then calculate all the possible outcomes.


Solution

  • I don't know how to create a method that can read the expression given, and then calculate all the possible outcomes.

    OK, so let's start with the task breakdown into subtasks. Here's what you need to do ...

    1. Parse the string you get as input into some internal data structures used by your program. This is a hard task. Make sure to cover relevant methods by unit tests.
    2. Calculate the truth tables. This is easier. You just need to iterate over all possible sets of inputs. These will be binary numbers from 0 to 2^n-1 where n is the number of boolean inputs.

    Let's see what resources you can use ...

    1. For the parse part you can adapt this
    2. To generate all possible inputs you can use this

    Also, please, make sure to cover your methods by unit tests. Its easy to make a mistake in complicated logic like this, which will take hours to debug. Therefore, unit tests will save you loads of time.

    Does this solve your problem ? Tell me in the comments.