Search code examples
clogicboolean-logiccircuit

Fill n input values on a truth table


I need an algorithm that produces all the initial boolean values of a truth table of size n.

Ex)

Size = 1: 1)T F
Size = 2: 1)T T F F  2)T F T F
Size = n: ?

The format is not important right now, but ideally its in the form:

for(int i = 0; i<n; i++){
   //do something 
}

My ultimate goal is to run a complete test of a boolean circuit on all possible values. The circuit is correctly implemented, but I need a way to test all permutations of inputs on a circuit that takes n inputs. So the end function looks like:

static void completeTest(Circuit *circuit){
    double num_inputs = getNumInputs(circuit);
    double perm = pow(2,num_inputs);
    for(int i = 0; i<perm; i++){
       //do something
    }
}

Solution

  • Try this:

    char values[] = {'F', 'T'};
    unsigned long long perm = 1ULL << n;
    for (unsigned long long i = 0; i < perm; i++) {
        for (unsigned int j = 0; j < n; j++) {
            printf("%c",values[(i >> j) & 1]);
        }
        printf("\n");
    }