This question already has answers here:
Building a math expression evaluator
(2 answers)
Closed 7 years ago.
I'm implementing a calculator in C ++ that respects the priorities of parentheses. I am trying to use std :: string :: find_last_of to find the last occurrence of ( and std :: string :: find to find the first occurrence of ). Once that is done, I reckon the content of the extracted substring and continuing with the rest of the string.
For example:
1 + 1 * (9 * (11-1 + 2))
I find the last occurrence of (, the first of ) and calculating 11-1 + 2. And so it continues.
Is this the right approach to this problem or is there something better?
Thank you.
You can use Reversed Polish Notation:
You will need to convert the expression into reversed polish notation and then implement a stack based algorithm to pop and push to the final answer.
Have a look at the Shunting- Yard algorithm here: To convert the expression into RPN.
https://en.wikipedia.org/wiki/Shunting-yard_algorithm
Also Have a look at
Writing a simple equation parser
For help to implement the stack, have a look here:
C++ Calculator using Stacks and Queues
One of the standard approaches to this problem consists of 2 steps:
1) Convert your expression to Reverse Polish notation: https://en.wikipedia.org/wiki/Reverse_Polish_notation using Shunting-yard algorithm https://en.wikipedia.org/wiki/Shunting-yard_algorithm
2) Evaluate converted expression using stack.
The another way to do this:
1) Easy step: Write Backus–Naur Form of your expressions https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form
And after you have 2 options:
2a) Build Finite-State Machine: https://en.wikipedia.org/wiki/Finite-state_machine (exists a lot of tools to do this: ANTLR, ...).
2b) Recursive descent method: https://en.wikipedia.org/wiki/Recursive_descent_parser
Related
This question already has answers here:
Regex multiplication
(2 answers)
Closed 2 years ago.
Is there possible with reg ex to find a string, say xxVAR1, xxVAR2, xxVAR3, where VARx is a number and for each match increase VARx say by 20%?
No, regex is pattern finding system. It cant calculate by its own. What you can do is find the first one by regex, then extract, calculate in your programming language and create a new regex. But there could be better ways around this task. Regex has no understanding of the math in numbers, for it every number is just a character that could be found.
You cannot exactly achieve what you want using regex. You have to use regex in addition to some high level language.
You can use this regex as a base
/(..VAR[0-9]{1})/
You can use Python or language of your choice to achieve following
regex = '/(..VAR[0-9]{%num%})/'
for i in range(1, 5):
new_regex = regex.replace('{%num%}', str(i))
# Do whatever you want
This question already has answers here:
How would you count occurrences of a string (actually a char) within a string?
(34 answers)
Optimized version of strstr (search has constant length)
(5 answers)
Closed 7 years ago.
What is the most efficient way to count a number of occurrences of a substring in another string in C++? For example, I have a very huge string like
"GQWHIWQGHWGGEEEGQIHIGWHIQWGHIEEEGPHIQPIWGHQPWGPHEEEGQIHWPWGQHPQWGEEE"
and I want to count how often "EEE" occurs.
I could go step by step in a for loop and check every letter if it's an E and if so, count them and if there are 3 es, increment a counter, but I guess there is a more efficient way of doing this.
Maybe a string function? I just wasn't able to find or google a suitable one.
I am searching for a clean C++11 solution.
Well, if you want a fast and efficent solution, take a look at Knuth–Morris–Pratt algorithm - it takes only O(N+M) to search.
If you want something in STL style, then take a look at std::string::find
This question already has answers here:
Evaluate mathematical expression from a string using VB
(3 answers)
Closed 4 years ago.
I am developping a calculator function in Visual Basic. I think there is no basic one in the default .NET libraries.
I use System.Data.DataTable.Compute() to calculate the normal Math expression. But I want my function to solve functions like Sinus() or Round() as well.
Currently I am using Regex for this. For example for functions with one argument I use
Dim expr As String = Regex.Replace(Term, "(?<func>[A-Za-z]*?)\((?<arg1>[0-9,.]*?)\)", AddressOf FunctionLibrary.Funcs1)
the Sinus() function would look like this: sin(Number).
But this only allows to write Doubles or Integers into the argument. I can not write inner functions or even another math expression between the parentheses.
If I would write more functions as an argument, Regex would detect the first ")" inside the function, which is the closing parenthese of the inner function, as the end of the outer function.
Is there any way to make Regex recognize that theres an inner function as well?
If anyone knows an Evaluate() function for Visual Basic which is in the default .NET libraries, this might help me as well
Is there any way to make Regex recognize that theres an inner function as well?
No, there is not. Regular expressions, as the name implies, solve Regular grammars and simple mathematical expressions are Context-Free. Regular expressions do not have a stack to match arbitrary expressions. For example, distinguishing between (()) and ()() require at least one character of lookahead (or backtracking). Yes, PCRE-style regular expressions can let you create a fixed number of lookahead characters, but so far as I know you have to specify the number of characters, and anyway this is not going to solve your problem.
Evaluating arithmetic expressions require handling precedence, subexpressions, possibly variables and types. Regular expressions cannot do this, attempting to do it with regular expressions will lead you into a pit of failure.
Nor are they even necessary. Evaluating mathematical expressions is a solved problem and there are dozens of parsers and evaluators written, tested, and ready for you to drop into your application. You have not given us enough information to decide which one would be best for you, and anyway Stack Overflow is not a tool advocacy site. You could start by going through the list at Gary Beene's Equation Parser review.
Is there any function in C++ (included in some library or header file), that would count an expression from string?
Let's say we have a string, which equals 2 + 3 * 8 - 5 (but it's taken from user's keyboard, so we don't know what expression exactly it will be while writing the code), and we want this function co count it, but of course in the correct order (1. power / root 2. times / divide 3. increase / decrease).
I've tried to take all the numbers to an array of ints and operators to an array of chars (okay, actually vectors, because I don't know how many numbers and operators it's going to contain), but I'm not sure what to do next.
Note, that I'm asking if there's any function already written for that, if not I'm going to just try it again.
By count, I'm taking that to mean "evaluate the expression".
You'll have to use a parser generator like boost::spirit to do this properly. If you try hand-writing this I guarantee pain and misery for all involved.
Try looking on here for calculator apps, there are several:
http://boost-spirit.com/repository/applications/show_contents.php
There are also some simple calculator-style grammars in the boost::spirit examples.
Quite surprisingly, others before me have not redirected you to this particular algorithm which is easy to implement and converts your string into this special thing called Reverse Polish Notation (RPN). Computing expressions in RPN is easy, the hard part is implementing Shunting Yard but it is something done many times before and you may find many tutorials on the subject.
Quick overview of the algorithms:
PRN - RPN is a way to write expressions that eliminates the need for parentheses, thus it allows easier computation. Practically speaking, to compute one such expression you walk the string from left to right while keeping a stack of operands. Whenever you meet an operand, you push it onto the stack. Whenever you meet an operation token, you calculate its result on the last 2 operands (if the operation is binary ofcourse, on the last only if it is unary) and push it onto the stack. Rinse and repeat until the end of string.
Shunting Yard really is much harder to simply overview and if I do try to accomplish this task, this answer will end up looking much like the wikipedia article I linked above so I'll save that trouble to both of us.
Tl;DR; Go read the links in the first sentence.
You will have to do this yourself as there is no standard library that handles infix equation resolution
If you do, please include the code for what you are trying and we can help you
This question already has answers here:
Math operations in regex
(3 answers)
Closed 8 years ago.
i am wondering of it is possible to do some simple Math on RegEx Variable values.
E.G.:
I am looking for all two-digit numbers is a textfile and would like to multiply them by 10.
Is simple regex able to do this or do i need to use a more complex script for that?
thanks!
Multiply two-digits number is like appending 0 at the end of the numbers. So that can be done with any regular expression that support replace and capturing group.
For example, here is Python code:
>>> re.sub(r'\b(\d{2})\b', r'\g<1>0', 'There are 10 apples.')
'There are 100 apples.'
But what you want is multiply by arbitrary number, then you need the regular expression engine that support some kind of callback / evaluation.
>>> re.sub(r'\b(\d{2})\b', lambda m: str(int(m.group(1)) * 5), '10 apples.')
'50 apples.'