Beta
Advanced Calculator!
Description:
(In some days will be available in JS) Your task is: When we program there are situations where we need to do calculations, so our way of Applying a formula is storing in variables and then joining them if the expression is complex.
What about if we can just do that?
int result = Calculator.evaluate("3^2-((2+3)^3*8-4*(6-2^0))");
//result = -971.0
You may be thinking... well... i can do that directly
int result = 3*3-((2+3)*(2+3)*(2+3)*8-4*(6-1));
// and result value is the same (-971)
But what about if you have large exponents, lot of parenthesis, summations...?
I propose you to develop a method called public static double evaluate(String expression){...}
(in Calculator
class) that returns a double value giving an expression as a parameter.
Expression can contain these operators:
+ -> "3+5"=8
- -> "5-3"=2
* -> "5*3"=15
/ -> "6/3"=2
^ -> "9^0.5"=3
sum$from,to,'expression'$ -> {
from represents an integer > -1
to represent an integer >= from
}
eg of sum operator:
sum$1,8,'x'$ = 1+2+3+4+5+6+7+8 = 36
sum$1,4,'x^2-1'$= (1^2-1)+(2^2-1)+(3^2-1)+(4^2-1) = 26
sum$0,5,'1/(x+1)'$= 2.45
(sum$1,10,'x-1'$/2)^2 = 506.25
and so on...
Observations:
1.) Do not take care of Arithmetic Exceptions (not difficult, but for making a shorter kata; this will be not tested)
2.) If an expression is not valid throw IllegalArgumentException.
3.) A expression can contains another expression
4.) Do not take care about sum indexes (that (to) must be greater or equal than (from) and (to) greater than (-1))
5.) Remember the priority of operations (first exponentiation, then parenthesis, then product and division, and then sum and subtraction)
6.) Any number in the expression can be an integer or a double value.
7.) Decimal separator is a dot.
8.) You must check if a expression is correctly written (only based on parenthesis: if the order of the parentheses is valid, then evaluate, else, throw IllegalArgumentException)
8.) Feel free to do and use whatever, there are no limitations!!!!
If you have any doubt, any suggestion…., let me know!
Happy coding ;-)
TDRS
Mathematics
Fundamentals
Algorithms
Parsing
Strings
Similar Kata:
Stats:
Created | Dec 23, 2016 |
Published | Dec 24, 2016 |
Warriors Trained | 142 |
Total Skips | 32 |
Total Code Submissions | 291 |
Total Times Completed | 13 |
Java Completions | 13 |
Total Stars | 11 |
% of votes with a positive feedback rating | 94% of 8 |
Total "Very Satisfied" Votes | 7 |
Total "Somewhat Satisfied" Votes | 1 |
Total "Not Satisfied" Votes | 0 |
Total Rank Assessments | 8 |
Average Assessed Rank | 2 kyu |
Highest Assessed Rank | 2 kyu |
Lowest Assessed Rank | 3 kyu |