954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Algorithm doubt

Hi can anyone help me in doing the following

Given n Boolean variables x1,x2,…..xn, we wish to print all possible combinations of truth values they can assume. For instance, if n=2, there are four possibilities : true, true; false, false; false, true; true, false;:-|

Karthi Msc
Newbie Poster
2 posts since Sep 2006
Reputation Points: 14
Solved Threads: 0
 

Simple. Just use nested for loops.

bool x1[2] = {true, false}
bool x2[2] = {true, false}
for ( i = 0 ; i < 1; i++ )
          for ( j = 0 ; j < 1; j++ )
                  print x1[i], x2[j];



will print the answer for two variables. Expand it for n variables.

WolfPack
Postaholic
Moderator
2,051 posts since Jun 2005
Reputation Points: 572
Solved Threads: 115
 

Maybe something like this which will implement a basic AND logic will help you understand the thing better:

int main ()
{
    bool first [] = {true, false} ;
    bool second [] = {true, false} ;

    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 2; ++j) {
            cout << boolalpha << first [i] << "  AND  " << second [j] << "  =>  " << (first[i] && second [j]) ;
            cout << endl ;
        }
    }
    return 0 ;
}


Hope it helped, bye.

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

for ( i = 0 ; i < 1<<N ; i++ )
Just print out the binary representation of i to N bits of precision.
Easy money.

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You