Truth table input generation

2019-08-13 11:48发布

For given n inputs, I need to generate all possible input combinations using C++

eg. n =4

I need to get,

1010101010101010

1100110011001100

1111000011110000

1111111100000000

(EDIT : In case this is not clear, these are the input combinations read column-wise)

I need these to perform operations like & and | so it would be best if I get them in their integer representation as n different variables.

I tried doing it using bitset for 32 input combinations but it took a long time to process. I was hoping if you guys had any ideas on a better implementation?

EDIT : Example when n=3

10101010

11001100

11110000

4条回答
小情绪 Triste *
2楼-- · 2019-08-13 12:15

Your question doesn't make that much sense but hopefully this is somewhat to what your looking for:

#include <stdio.h>

main(){

        int n = 3;
        int total = (n*n)-1;
        char poss[total];
        int i = 0;
        for (i = 0; i < total; ++i){
                poss[i] = i;
                printf("%d \t",poss[i]);
                printf("%d \n",poss[i] & 1);
        }

}

So n is your n as you said, total is the total number of possibilities that can be held in n (3) bits. Then a char array is setup, you can use int if this is too short. All possibles are added. This is because a truth tables possibilities are the same as that of what can be in those many bits.

The second printf shows an AND operation, here we would be doing e.g.:

000 AND 001 => 000
001 AND 001 => 001
010 AND 001 => 000
011 AND 001 => 001

See Alfs code for formatting in the way you want (especially in binary not in decimal like this)

查看更多
男人必须洒脱
3楼-- · 2019-08-13 12:24

n=4 would be

0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111

not what you generated (not sure what you mean by "n")???

查看更多
相关推荐>>
4楼-- · 2019-08-13 12:29

Your question is still utterly incomprehensible to me.

The code below, however, reproduces your example output.

#include <iostream>

int main()
{
    using namespace std;

    int const   n       = 3;
    int const   nBits   = 1 << n;

    int powerOf2  = 1;
    for( int i = 0;  i < n;  ++i )
    {
        for( int bitNum = 0;  bitNum < nBits;  ++bitNum )
        {
            cout << 1 - bitNum/powerOf2 % 2;
        }
        cout << endl;
        powerOf2 *= 2;
    }
}

Now I hope this wasn't homework. If it was then you're deceiving yourself and others by seeking answers on SO (which will bite you, and others, later). For homework, please indicate clearly that it is homework, then we can adjust our answers correspondingly.

Cheers & hth.,

查看更多
够拽才男人
5楼-- · 2019-08-13 12:39

Here is a short implementation that generates that output:

void print_mask(int n){
    for (int level = 0; level < n; level++){
        for (int i = (1<<n)-1; i>=0; i--)   // we'll always output 2**n bits
            printf("%d", (i >> level) & 1);
        printf("\n");
    };
};
查看更多
登录 后发表回答