I have to write a program where the input is a Boolean Expression and the ouput is the corresponding sum of minterms for that particular expression.
My idea is that i need to convert the infix boolean expression to a postfix expression. From there I need to construct the truth-table for the function. Once i get the truth-table i can easily get the sum of minterms format.
So far I have wrote the code to convert infix to postfix, and i can print the sum of minterms. I have confusion regarding the construction of the truth-table, i m having so many ideas as how to do it that i dont know which one to follow, and most importantly i dont know if that's the correct way to do it. I was looking for some advice as how to construct the truth-table efficiently from the postfix expression. The idea i currently have is to keep track of the number of variables and run a loop from 0 to 2^(no of variables) -1, and then use bitwise operators to assign each boolean variable itz appropriate values to finally evaluate the expression.
These are the functions i have been working on:
void topostfix(char *infix,Queue<char> &post)
{
Stack<char> inter;
char last = 0;
char temp;
for(; *infix; ++infix)
{
if (precedence(*infix, 1) > precedence(last,2))
{
inter.Push(last = *infix);
if((temp = *(++infix)) == '\'')
post.Append(temp);
else
--infix;
}
else if(precedence(*infix,1) <= precedence(last,2))
{
while(!inter.isEmpty())
{
if(precedence(temp = inter.Pop(),1) >= precedence(*infix,1))
{
if(temp != '(' && temp != ')')
post.Append(temp);
}
else
{
if(temp != '(' && temp != ')')
inter.Push(last = temp);
break;
}
}
if (*infix != '(' && *infix != ')')
inter.Push(last = *infix);
}
}
while(!inter.isEmpty())
post.Append(inter.Pop());
post.Print();
}
int precedence(char token, int type)
{
if((token >= 'A' && token <= 'Z') || (token >= '1' && token <= '9'))
return 9;
else if ( token == '*' || token == ' ')
return 4;
else if ( token == '+')
return 3;
else if ( token == '(')
return (type == 1? 9: 2);
else if (token == ')')
return (type == 1? 2: 9);
else
return 0;
}
and also this function to prouduce a minterm:
void minterm(int nmin,int nvar, Queue<char> &q)
{
unsigned int mask = 1 << (nvar -1);
int i;
for(i = 0; i < nvar; ++i, mask >>= 1)
{
if ((nmin & mask) == 0)
{
q.Append('A' + i);
q.Append('\'');
}
else
{
q.Append('A' + i);
q.Append(' ');
}
}
return;
}
How do I go about defining a function to get the truth-table?