Generating truth tables in Java
Asked Answered
C

8

11

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.

Cusco answered 23/5, 2012 at 15:28 Comment(0)
R
18

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

public class TruthTable {
    private static void printTruthTable(int n) {
        int rows = (int) Math.pow(2,n);

        for (int i=0; i<rows; i++) {
            for (int j=n-1; j>=0; j--) {
                System.out.print((i/(int) Math.pow(2, j))%2 + " ");
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        printTruthTable(3); //enter any natural int
    }
}
Running answered 25/5, 2012 at 21:2 Comment(1)
This is good. You can also replace the calls to Math.pow(2,n) with (1 << n)Pantalets
S
13

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.

int n = 3;
for (int i = 0 ; i != (1<<n) ; i++) {
    String s = Integer.toBinaryString(i);
    while (s.length() != 3) {
        s = '0'+s;
    }
    System.out.println(s);
}
Spahi answered 23/5, 2012 at 15:31 Comment(1)
To make it dynamic you should replace s.length() != 3 with s.length() != nFoldboat
K
2

The magic of recursion:

public static void main(String args[]) {
    int size = 3;
    generateTable(0, size, new int[size]);
}

private static void generateTable(int index, int size, int[] current) {
    if(index == size) { // generated a full "solution"
        for(int i = 0; i < size; i++) {
            System.out.print(current[i] + " ");
        }
        System.out.println();
    } else {
        for(int i = 0; i < 2; i++) {
            current[index] = i;
            generateTable(index + 1, size, current);
        }
    }
}
Kickback answered 23/5, 2012 at 15:34 Comment(0)
T
1

If you look at what you're generating, it appears to be counting in binary. You're going to be counting to 2^(n) - 1 in binary and spitting out the bits.

Tris answered 23/5, 2012 at 15:31 Comment(0)
G
0

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<

public void  generate(int n){
    for (int i=0 ;i!=(1<<n);i++) {
        String binaryRep = Integer.toBinaryString(i);
        while (s.length() != n) {
            binaryRep = '0'+binaryRep;
        }
        System.out.println(s);
    }
}

you can make that using recursion also :

public void generateRecursively(int i , int n){
    if(i==(1<<n))
        return;
    else{
        String temp = Integer.toBinaryString(i);
        while(temp.length()<n){
            temp = '0'+temp;
        }
        System.out.println(temp);
        generateRecursively(i+1,n);
    }
}
Glasswork answered 16/5, 2014 at 20:2 Comment(1)
In the non-recursive function, it should be 'while (binaryRep.length()...', as well as 'System.out.println(binaryRep);' (binaryRep instead of s).Renewal
D
0

A longer take to your problem

import java.util.Scanner;
    public class tt{
        boolean arr[][];
        boolean b=false;
        boolean[][] printtt(int n){
            for(int i=0;i<n;i++){
                for(int j=0;j<(Math.pow(2,n));j++){

                        if(j<Math.pow(2,n-1)){
                            arr[j][i]=b;
                        }
                        else{
                            arr[j][i]=!b;
                        }
                }
                }
                return(arr);
            }


        public static void main(String args[]){
            Scanner sc=new Scanner(System.in);
            System.out.println("Input values count");
            tt ob=new tt();
            int num=sc.nextInt();int pownum=(int)Math.pow(2,num);
            boolean array[][]=new boolean[pownum][num];
            array=ob.printtt(num);
            for(int i=0;i<num;i++){
            for(int j=0;j<(Math.pow(2,num));j++){

                    System.out.println(array[j][i]);
                }
        }
    }
    }
Danube answered 20/8, 2015 at 6:50 Comment(0)
T
0

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)

Trivium answered 13/11, 2016 at 3:37 Comment(0)
I
0

This simple program stores your truth table of any given number of inputs in an int array and prints it out.

import java.util.Scanner;

public class Main{

public static class TruthTable {
    public static int rows;
    public static int nodes;
    public static int[][] tt = new int[0][0];


    TruthTable(int n) {
        this.nodes = n;
        this.rows = (int) Math.pow(2,n);
        tt = new int[rows][nodes];

        for (int i=0; i<rows; i++) {
            for (int j=n-1; j>=0; j--) {
                tt[i][j] = (i/(int) Math.pow(2, j))%2;
            }  
        }
    }   

    void printTable(){
        for (int i=0; i<rows; i++) {
            for (int j=nodes-1; j>=0; j--) {
                System.out.printf("%d ", tt[i][j]);
            }
            System.out.println();

        }

    }
}
public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);
    System.out.println("Enter Size of Population: ");
    int numberOfNodes = myObj.nextInt();
    TruthTable myTable = new TruthTable(numberOfNodes);
    //TruthTable.printTruthTable(3);
    System.out.println();

    myTable.printTable();

}

}

Inroad answered 4/4, 2021 at 11:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.