0
Single Line Calculator
Hello everyone!!! How can I create a single line calculator without eval in c# ? input: 12+3*4 output:24
3 Answers
+ 2
on one line it would be difficult, you could try chaining map and filter methods on a really long line but yeah it would still be tough.
eval is really the ideal for one line execution if you need something like that.
PS. Some websites have people that have mastered obfuscation, like codewars. That tackle these kind of problems in creative ways.
+ 2
First of all, tear apart the expression, meaning, divide each number and mathematical operation.
Now we have: [12, +, 3, *, 4]
Now you can manipulate the datatypes and calculate everything. You would also need to consider that multiplication comes before simpler mathematical operations etc etc..
+ 2
- you can parse the input string with a regular expression to get the operands (numbers) and operator signs
- build an AST (abstract syntax tree) from these elements, based on operator precedence
- execute the AST
It could also be a strategy to find the highest precedence part of the string (number operator number), execute the operation and replace the result in the string. Then continue until you have only a single numbers.
If you want to process parentheses too, it can complicate things, but recursive algorithm can help here to process subexpressions.