Search code examples
c#parsingtruthtable

Truth Table for an expression( as string )


I want to compute the truth table for an expression(valid logical expression) input by the user as a String. Can anybody post an existing solution to this or guide me in doing so?? I am thinking of using a BitArray (of size 2^no. variables) as the output (the truth table). But do not know how to start. Please help me with this.

Ex:-

 p or q or r

Should result as

 False True True True True True True True 

And

 a and b 

Should result as

 False False False True 

Solution

  • First, you will need to parse the string input to find the variables and the structure of the expression (i.e. what operations are applied to what sub-expressions).

    Once you are done with that, you can represent the state of the variables as a binary integer. Whith this representation you can start from 0 (meaning all variables are false) and increment the integer representation by 1 for each row of the truth table. This way you can account for all possible combinations exactly once.

    Then apply the values of the variables to the expression (subtitute true/false according to the bit value of the integer for the variables in question) and cacluate the value of the expression.

    If you want compact representation of the result, you can just store the expression values for each input combination in a linear collection (e.g. vector) where the index of the output corresponds to the above integer representation of the variable values. If you know what variable maps to which bit of the input, you can re-create the full table any time you need to (e.g. for printing)