Question

I want to write a program which shows combinations of True and False. This is only one part of program. I wrote other parts but I can't find a solution to this.

For example :

input: 2
output:
    T T
    T F
    F T
    F F

input: 4
output:
    T T T T 
    T T T F 
    T T F T 
    T T F F 
    T F T T 
    T F T F 
    T F F T 
    T F F F 
    F T T T 
    F T T F 
    F T F T 
    F T F F 
    F F T T 
    F F T F 
    F F F T 
    F F F F 

If you don't want to write code, you can explain or use pseudo-code or Python :)

Was it helpful?

Solution

What about simple conversion of integers to binary format?

def possibilities(bitcount):
    for i in reversed(xrange(2**bitcount)):
        yield ("{0:0" + str(bitcount) + "b}").format(i)

def prettyprint(bitcount):
    for p in possibilities(bitcount):
        print " ".join(p.replace("0", "F").replace("1", "T") + "/")

If you need to process the possibilities programatically, a bunch of bit operations will be enough and you don't even need the string conversion.

OTHER TIPS

There you go:

def PrintTruthTable(size):
    for i in range(0,1<<size):
        print ' '.join(['T' if (i>>j)&1==1 else 'F' for j in range(0,size)])
  • The i index iterates through every possible combination between 0 and 2^size-1
  • The j index iterates through every bit in the combination given by the value of i

This might be easier for you to understand:

def PrintTruthTable(size):
    for i in range(0,1<<size):
        line = ''
        for j in range(0,size):
            if (i>>j)&1 == 1:
                line += 'T'
            else:
                line += 'F'
        print line

The simplest way to do so would be using binary code.

We will simply write the binary codes for all numbers from 0 to the maximum number we can make using the number of binary digits equal to the input.

Say, we input 3. The maximum number we can make using 3 binary digits, is 111 i.e. 7. So we will write binary code for all number from 0 to 7.

Which are:

000=0

001=1

010=2

011=3

100=4

101=5

110=6

111=7

To write T or F, we will simply put a condition where T is printed for 1 and F for 0.

Here is the code:

#include<stdio.h>
#include<string.h>

int num_of_digits;

void bitcode(int num){
    int current_digit_num=num_of_digits;
while(current_digit_num!=0){
    if(num%2==1)
        printf("T ");
    else
        printf("F ");
    num=num/2;
    current_digit_num--;
}
}

main()
{
    int current_num,value;
scanf("%d", &num_of_digits);
value=pow(2,num_of_digits);
for(current_num=0;current_num<value;current_num++){
    bitcode(current_num);
    printf("\n");
}
return 0;
}

NOTE: This method works because from 0 (000..) to the maximum number (111..), we go through all the possible combinations we can make to fill that much number of digits with 0 or 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top