Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Map;
- import java.util.Optional;
- import java.util.Stack;
- import java.util.regex.Pattern;
- interface DoubleBiFunction {
- double apply(double a, double b);
- }
- enum Operator {
- ADD("+"),
- SUBTRACT("-"),
- MULTIPLY("*"),
- DIVIDE("/");
- String op;
- Operator(String op) {
- this.op = op;
- }
- private static final Map<String, DoubleBiFunction> fn = Map.of(
- "+", (a, b) -> a + b,
- "-", (a, b) -> a - b,
- "*", (a, b) -> a * b,
- "/", (a, b) -> a / b
- );
- private static final Map<String, Operator> reverseMapper = Map.of(
- "+", ADD,
- "-", SUBTRACT,
- "*", MULTIPLY,
- "/", DIVIDE
- );
- public double call(double a, double b) {
- return fn.get(op).apply(a, b);
- }
- static Optional<Operator> ofNullable(String op) {
- return Optional.ofNullable(reverseMapper.get(op));
- }
- }
- class Calc {
- public double evaluate(String expr) {
- Stack<Double> expressions = new Stack<>();
- Pattern.compile("(\\s)")
- .splitAsStream(expr)
- .filter((s) -> !s.isEmpty())
- .forEach((s) -> Operator.ofNullable(s)
- .ifPresentOrElse(
- (op) -> {
- var right = expressions.pop();
- var left = expressions.pop();
- expressions.push(op.call(left, right));
- },
- () -> expressions.push(Double.parseDouble(s))
- )
- );
- return expressions.isEmpty() ? 0 : expressions.pop();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement