First, the question of the proposed
If we have the and/or expression shown below:
a*[b*[c+d]*e+f]+g
The following expressions are to be obtained after simplification:
a*b*c*e+a*b*d*e+a*f+g
Letters and operators allowed in an expression
{A-Z, a-z, [,],*,+}
where "[,]" represents parentheses, allows nesting, "*" means logical operators "and", "+" denotes logical operators "or", and "*" has precedence over "+".
Ii. Solutions
In the compiler principle, there is a Top-down analysis method ll (1), its core algorithm is "recursive descent method", its specific theory interested friends can refer to some compiler principles books. First of all, let's take a look at a compiler principle in the textbook, "Recursive Descent method" to "evaluate the expression" of the resulting formula:
exp->exp addop term|term
addop->+|-
term->term mulop factor|factor
mulop->*
factor->(exp)|number
WHERE "exp" represents an expression for the value to be evaluated; ADDOP "represents" + "and"-"operator," term "represents an expression connected with" * "," Mulop "represents" * "," factor "represents the product factor, it can be a number, or it can be an expression.
In this way, I have come up with the following formula that corresponds to the problem raised at the beginning of this article:
exp->term { OR term }|term
OR->+
term->term AND factor|factor
AND->*
factor->[exp]|letter
letter->[A-Z]|[a-z]
The removal of left recursion is shown below:
exp->term { OR term }
OR->+
term->factor { AND factor }
factor->letter|[exp]
AND->*
letter->[A-Z]|[a-z]
That way, it's easy to turn it into code. For example, the pseudo code that converts the expression "Exp->term {OR term}" is as follows:
CString exp()
{
CString temp = _T("");
try
{
temp = Term();
while( 当前还没有到输入串的末尾 && 下一个将要扫描的字符为OR )
{
temp += "+";
Match(OR);//字符匹配,用户判断将要扫描的字符是否为所期望的字符,并且推动扫描串的前进
temp += Term();
}
}
catch(CError& error)
{
throw error;
}
return temp;
}
Other production corresponding to the code similar to the specific details are not described, please refer to the source program.
Three, the Operation effect chart
Iv. concluding remarks
This is the first time I have published an article in the vckbase, there must be many deficiencies, I hope you can point out the criticism
^-^. At the same time, I also feel deeply a computer-learning students, rich programming practical experience is important, but if there is a rich theoretical foundation as a strong backing, then we will be able to write the program when we can easily feel that the writing program is a real enjoyment ^ ^.
This article supporting source code