Answer the question
In order to leave comments, you need to log in
Calculator Implementation: Which Algorithm to Use?
Greetings! I am writing a calculator app with binary/unary functions and brackets. Now everything works like this:
1. All operands and operators are thrown onto the stack
2. When you press the "=" button, the marshalling yard algorithm is launched, which then calculates the result in RPN
However, the task is to be able to see some intermediate result, as in standard calculators (for example, for iPhone). That is, the unary expression is counted separately (when you click on the square root with the expression 2 + √(3+6), the result "3" is displayed, and then, if you then click "+", then the entire expression is considered, taking into account the priority). And the binary expression is considered taking into account the priority and gives the result of all available calculations (if the priority of the next operation is less than the previous one).
Of course, every time you click on a binary operation, you can count everything anew (setting restrictions on priorities), and when you click on a unary one, you can count a separate region, but something seems to me that this is not very optimal.
Are there any other options?
PS Probably, several clarifications are required:
a). The current implementation does a fine job of counting a ready-made expression;
b). As far as I've seen, calculators consider a binary operation only when the next operation with a priority lower than it is encountered (That is, when the user enters 2 + 3 * , he does not get the addition result, because the current operation has a priority, and if after that he wants a second raise the operand to a power, then the calculation of two operations will be postponed: 2 + 3 * 4 ^ 2);
in). The program has a GUI, so some intermediate result is needed;
G). Swift language (although this is not important, but suddenly);
Answer the question
In order to leave comments, you need to log in
The issue was resolved.
As I expected, it was necessary to create a stack of deferred binary operations. When adding a new binary operation to the stack, you need to compare its priority with the priority of the previous operation, and if the new operation has a lower priority, then execute the previous one. It's almost the same with brackets, only a flag is used there.
If possible, I will post the solution on GitHub.
Thank you all for your help!
recalculate everything at once
PS it will be better if it is displayed like this
2 + √(3+6)
2+3
5
Parse through operators from left to right.
When valid expressions - calculate the same points ("stack" and RPN).
From left to right when popping from the stack - replace the original expression:
Validation of the expression at each step is checked during the conversion of the expression to the stack (point 1 in the question).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question