Problem
Truth Table implementation: Write a function which takes integer as In put parameter (let's say n), print all True (T) , False (F) combinations n times. Here is the example:
for n = 1
Output :
T
F
for n = 2
Output :
T F
F T
For n = 3
Output :
T T T
T T F
T F T
T F F
F T T
F T F
F F T
F F F
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Print truth table
Created Date : 27-06-2013
Last Modified :
============================================================================
*/
#include <iostream>
#include <iomanip>
#include <iterator>
#include <algorithm>
#include <bitset>
#include <queue>
using namespace std;
void GenerateTruthTable(const int n, vector<string>& vec)
{
queue<string> q;
string tf;
tf.reserve(n);
q.push(tf);
while(!q.empty()){
string str = q.front();
q.pop();
if(str.size() < n){
str.push_back('F');
q.push(str);
str.pop_back();
str.push_back('T');
q.push(str);
}
else{
vec.push_back(str);
}
}
}
int main(int argc, char* argv[])
{
for(int i = 0; i < 6; ++i){
vector<string> output;
cout << "---------------------------" << endl;
GenerateTruthTable(i, output);
copy(output.begin(), output.end(), ostream_iterator<string>(cout, " "));
cout << endl;
}
return 0;
}
Output
---------------------------
---------------------------
F T
---------------------------
FF FT TF TT
---------------------------
FFF FFT FTF FTT TFF TFT TTF TTT
---------------------------
FFFF FFFT FFTF FFTT FTFF FTFT FTTF FTTT TFFF TFFT TFTF TFTT TTFF TTFT TTTF TTTT
---------------------------
FFFFF FFFFT FFFTF FFFTT FFTFF FFTFT FFTTF FFTTT FTFFF FTFFT FTFTF FTFTT FTTFF FTTFT FTTTF FTTTT TFFFF TFFFT TFFTF TFFTT TFTFF TFTFT TFTTF TFTTT TTFFF TTFFT TTFTF TTFTT TTTFF TTTFT TTTTF TTTTT
Press any key to continue . . .