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)
prints:
0
1
printTruthTable(3)
prints:
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
And so on. I have been trying to implement it using recursion, but I just can't get it right.
here's my take on your problem, all written nice and tight in a small class, just copy/paste
notice how I used modulo2 (the % sign) to get 0's and 1's from the loop indices
This is not a truth table - rather, it's a table of binary numbers. You can use Java's
Integer.toBinaryString
method to generate the zeros and ones that you need; inserting spaces should be trivial.A longer take to your problem
The magic of recursion:
the truth table is base on the binary representation of the number but without removing leading zero's so what you would do is to loop from 0 to (1<
you can make that using recursion also :
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.
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)