Math expression parsing
Now we got a tree representing a mathematic expression. Our next job is to read those values and turn them into a mathematic expression that can be parsed and evaluated to get the values and compare with our desired result.
Recursive descent parser
A recursive descent parser is a top-down parser built from a set of recursive functions where each of the procedures implements one of the operators or value replacement in the equation. That is, our parser shall call each of the equation terms and each element of the function shall call the other to process a section of the equation and return the value to the caller, until we get the result [1], [2].
Replace variables for its values
Once we got our parser we must replace the values of each of the variables a, b, and c for the equation's value in order to implement the arithmetic operations and discern whether our value is closer or farther from the desired equation value.
string replaceVar(string exp){
int temp_index=0;
while(true){
temp_index = exp.find("a", temp_index);
if(temp_index==std::string::npos)
break;
exp.replace(temp_index, (unsigned)strlen(a.c_str()), a);
temp_index+=(unsigned)strlen(a.c_str());
}
temp_index=0;
while(true){
temp_index = exp.find("b", temp_index);
if(temp_index==std::string::npos)
break;
exp.replace(temp_index, (unsigned)strlen(b.c_str()), b);
temp_index+=(unsigned)strlen(b.c_str());
}
temp_index=0;
while(true){
temp_index = exp.find("c", temp_index);
if(temp_index==std::string::npos)
break;
exp.replace(temp_index, (unsigned)strlen(c.c_str()), c);
temp_index+=(unsigned)strlen(c.c_str());
}
return exp;
}
int temp_index=0;
while(true){
temp_index = exp.find("a", temp_index);
if(temp_index==std::string::npos)
break;
exp.replace(temp_index, (unsigned)strlen(a.c_str()), a);
temp_index+=(unsigned)strlen(a.c_str());
}
temp_index=0;
while(true){
temp_index = exp.find("b", temp_index);
if(temp_index==std::string::npos)
break;
exp.replace(temp_index, (unsigned)strlen(b.c_str()), b);
temp_index+=(unsigned)strlen(b.c_str());
}
temp_index=0;
while(true){
temp_index = exp.find("c", temp_index);
if(temp_index==std::string::npos)
break;
exp.replace(temp_index, (unsigned)strlen(c.c_str()), c);
temp_index+=(unsigned)strlen(c.c_str());
}
return exp;
}
References
[1] http://www.cplusplus.com/forum/general/93728/
[2] http://stackoverflow.com/questions/9329406/evaluating-arithmetic-expressions-in-c
[2] http://stackoverflow.com/questions/9329406/evaluating-arithmetic-expressions-in-c