Reputation: 47
I'm creating a program that will calculate the truth values for a boolean algebra equation. I need to find a good data structure that will be able to correctly process the order of operations of an equation involving AND, OR, NOT, and parentheses as well. The equation will be typed in by the user.
Upvotes: 4
Views: 1503
Reputation: 5647
Any type of "order of operation" objects are usually held in trees. It would look like this:
true OR false
for example) would be put into a nodeA final tree representation may end up looking something like this:
OR
___|__
| |
true AND
___|___
| |
false NOT
|
true
That would represent the statement:
true OR (false AND NOT true)
Upvotes: 2
Reputation:
A binary tree is the answer here.
Say you have expression A and B or C
, then the representation you're looking for would resemble this:
or
/ \
and C
/ \
A B
Note that the tree already encodes the precedence rules.
A simple solution would look like this:
class tree_node
{
public:
virtual ~tree_node() = default;
virtual bool evaluate() = 0;
};
class false_literal_node : public tree_node
{
bool evaluate() override
{
return false;
}
};
// Same goes for `true` literal...
class variable_node : public tree_node
{
bool evaluate() override
{
return value;
}
bool value;
};
class conjunction_node : public tree_node
{
bool evaluate() override
{
return lhs->evaluate() && rhs->evaluate();
}
std::unique_ptr<tree_node> lhs;
std::unique_ptr<tree_node> rhs;
};
You get the idea...
Evaluating an expression would then be to parse it (which would get you a tree) and then calling evaluate
on the root.
Upvotes: 1