Formula Algorithm for Compiler:
Advantages of this algorithm:
-????????? It replaces stack prefix infix and postfix algorithm.
-????????? It enables using large formula without affecting execution time.
-????????? It makes the compiler faster
-????????? It is simple and can be taught in school before university.
Begin:
Covert the formula into string for further processing.
calculate number of operands or number of operators.
Construct an 1d array of number of operands -1
Or number of operators.
(i.e in C++ type *A = new type[Operators -1];
Or type *A = new type[number of operands -2];
Such that type is the type operands (i.e : int, float, double).
Find out the most internal parenthesis calculate them
As A[0]= most internal parentheses from left to right{the greatest one got number of ( in string or number of ) the max one in string). And so on until including all them.
Replace the parentheses by calculated on (I.e A[0])? ?
Seeking for highest precedence from left and right(i.e if(operator == ‘*’ || operator =’ /’)
Replace them by A[i] and A[i+1]……………..etc. (it may calculate it with previous A[m] such that m < I;
Keep incrementing the index for each calculate pairs and replace them.
Use generated equations instead of formula.
Stop when one is left. Or index ==? NumberOfOperators -1, or NumberOfOperands -2
Tracking Algorithms:
Suppose we have y = (x1-x2) + ((x3 – x4)/x5 )– x6 *x7 / x8 – x9
Y = (x1-x2) + (A[0] /x5 )– x6 *x7 / x8 – x9
A[0] = x3 – x4;
Y = A[1] + (A[0] /x5 )– x6 *x7 / x8 – x9
A[1] = x1- x2;
Y = A[1] + A[2]– x6 *x7 / x8 – x9
A[2] = A[0]/ x5
Y = A[1] + A[2]– A[3] / x8 – x9
A[3] = x6 * x7
领英推荐
Y = A[1] + A[2]– A[4] – x9
A[4] = A[3] / x8
Y = A[5]– A[4] – x9
A[5] = A[1] + A[2]
Y = A[6]– x9
A[6] = A[5]– A[4]
Y = A[7]
A[7] = A[6] – x9
?
Now replace the formula with following equations:
A[0] = x3 – x4;
A[1] = x1- x2;
A[2] = A[0]/ x5
A[3] = x6 * x7
A[4] = A[3] / x8
A[5] = A[1] + A[2]
A[6] = A[5]– A[4]
A[7] = A[6] – x9
Finished []
Now this equations are recursive let’s generate associative shape from the end to beginning
A[7] = A[6] – x9
A[7] = (A[5] – A[4]) -x9
A[7] =(( A[1] + A[2] – (A[3]/x8) -x9
A[7] =(( ( x1-x2) +( A[0]/x5) – (x6*x7)/x8 -x9
A[7] = (x1-x2) + ((x3-x4)/x5) – ((x6*x7)/x8) -x9
Same as we have y = (x1-x2) + ((x3 – x4)/x5 )– x6 *x7 / x8 – x9
?
?
?
?
?
?