Search code examples
c++c++11vectortruthtable

convert truthTable result into Boolean statement


I am trying to convert back the result of the truth-table into a Boolean statement. For those who are not familiar I am going to write it detail.

I have a vector of string in a format like below. All string members inside vector have an equal length. Members are only composed by - or 0 or 1. for example vector v contain 3 member with the length of 5 for each member.

string vv[] = { "--1-0"  , "-1-1-" ,  "01-1-" };
std::vector<string> v(begin(vv), end(vv));

Each character of string represents another vector "A" member along with a Boolean operation. For instance,

first one --1-0 is (A[2] && !A[4])

I would like to convert my above vector v into

(A[2] && !A[4]) || (A[1] && A[3] ) || (!A[0] && A[1] && A[3])

What I want to do is to have a function with vectors v and A as inputs and the return is above Boolean statement. I am sure you have noticed that 1 is true, 0 is Not true and - is don't care status.

EDIT: I do NOT intend to solve a truthTable or Kmap. I already have the result. My result in the format of "v" vector. I want to create a link between V and A using Boolean statement.

Any suggestion is appreciated.


Solution

  • I suppose the problem is that I don't speak English well but isn't clear to me what do you exactly want.

    If you want a function that given a vector of std::string and a vector of bool return the bool value, according your indications, it's easy to do (hoping no errors made).

    You use std::begin() so I suppose C++11 is good for you

    #include <vector>
    #include <iostream>
    #include <stdexcept>
    
    bool singleStatement (const std::vector<bool>  & a,
                          const std::string        & s)
     {
       auto  ret = true;
    
       if ( a.size() < s.size() )
          throw std::runtime_error("invalid size");
    
       for ( unsigned  i = 0U ; i < s.size() ; ++i )
          switch ( s[i] )
           {
             case '-': break;
             case '1': ret &= a[i]; break;
             case '0': ret &= !a[i]; break;
             default:  throw std::runtime_error("invalid char"); break;
           }
    
       return ret;
     }
    
    bool statements (const std::vector<bool>        & a,
                     const std::vector<std::string> & v)
     {
       auto  ret = false;
    
       for ( const auto & s : v )
          ret |= singleStatement(a, s);
    
       return ret;
     }
    
    
    int main ()
     {
       std::vector<bool>         a { true, false, false, true, false };
       std::vector<std::string>  v { "--1-0"  , "-1-1-" ,  "01-1-" }; 
    
       std::cout << "statement is " << statements(a, v) << std::endl;
    
       return EXIT_SUCCESS;
     }