反向抛光给出错误答案

时间:2017-03-20 13:08:13

标签: java calculator rpn

我需要制作带有中缀表达式的计算器并使用rpn来评估它。

Java代码:

public RpnCalculator() {

}


public float eval(float arg1, float arg2, String operator) {
    switch (operator) {
        case PLUS:
            return arg1 + arg2;
        case MINUS:
            return arg2 - arg1;
        case MULTIPLICATION:
            return arg1 * arg2;
        case DIVISION:
            return arg2 / arg1;
        default:
            return 0;
    }
}

public String evaluateInfixExpression(String expression) {
    Stack<String> operators = new Stack<>();
    String[] args = expression.split(SPACE);
    Stack<String> values = new Stack<>();

    for (String arg : args) {
        if (isANumber(arg)) {
            values.push(arg);
            continue;
        }
        if (operators.isEmpty()) {
            operators.push(arg);
        } else if (precedence(arg) <= precedence(operators.peek())) {
            float result = eval(Float.parseFloat(values.pop()), Float.parseFloat(values.pop()), operators.pop());
            values.push(String.valueOf(result));
            operators.push(arg);
        } else if (precedence(arg) > precedence(operators.peek())) {
            operators.push(arg);
        }
    }


    while (!operators.isEmpty()) {
        float result = eval(Float.parseFloat(values.pop()), Float.parseFloat(values.pop()), operators.pop());
        values.push(String.valueOf(result));
    }

    return expression;
}

public int precedence(String operator){
    if (operator.equals(PLUS) || operator.equals(MINUS)){
        return 1;
    }
    return 2;

}

public boolean isANumber(String number) {
    if (number.matches("-?\\d+")) {
        return true;
    }
    return false;
}

}

并且效果很好,但有时会给出错误的答案... 对于我来说,我似乎遵循了分流码算法原则,但正如你所看到的,我实际上并没有将中缀转换为后缀,但我试着在运行中评估参数,也许这是一个问题。

例如表达式-2 + 6 * 8/3 * 18 - 33/3 - 11的评估值为286而不是264。应该有一些我无法注意到的错误,已经有两天了,所以请帮我。另外我在堆栈上阅读了很多关于RPN的线程,但似乎每个人都有不同的问题,所以我没有找到我的案例的答案。

谢谢。

3 个答案:

答案 0 :(得分:1)

我不是RPN专家,但是我注意到你正在评估从右到左顺序的参数,因此,在评估了乘法和除法后,你最终得到了这个:

operators = + - -
values = -2 288 11 11

然后你做(从右到左的顺序):

11 - 11 = 0     // would expect -22 here
288 - 0 = 288
-2 + 288 = 286

哪个没有给出正确的结果。

如果按从左到右的顺序进行评估,则会得到:

-2 + 288 = 286
286 - 11 = 275
276 - 11 = 264

所以我改变了你的代码:

public String evaluateInfixExpression(String expression) {
    Deque<String> operators = new LinkedList<>();
    String[] args = expression.split(SPACE);
    Deque<String> values = new LinkedList<>();

    for (String arg : args) {
        if (isANumber(arg)) {
            values.push(arg);
            continue;
        }
        if (operators.isEmpty()) {
            operators.push(arg);
        } else if (precedence(arg) <= precedence(operators.peek())) {
            float result = eval(Float.parseFloat(values.pop()), Float.parseFloat(values.pop()), operators.pop());
            values.push(String.valueOf(result));
            operators.push(arg);
        } else if (precedence(arg) > precedence(operators.peek())) {
            operators.push(arg);
        }
    }

    while (!operators.isEmpty()) {
        String v1 = values.removeLast();
        String v2 = values.removeLast();
        float result = eval(Float.parseFloat(v2), Float.parseFloat(v1), operators.removeLast());
        values.addLast(String.valueOf(result));
    }
    return expression;
}

答案 1 :(得分:1)

对于RPN,首先应将中缀表单转换为后缀表单。为此,您可以使用Dijkstra的Shunting-yard algorithm

此算法的示例实现:

public class ShuntingYard {
    private static boolean isHigerPrec(String op, String sub) {
        return (ops.containsKey(sub) && ops.get(sub).precedence >= ops.get(op).precedence);
    }

    public static Stack<String> postfix(String infix) {
        Stack<String> output = new Stack<>();
        Deque<String> stack  = new LinkedList<>();

        for (String token : infix.split("\\s")) {
            if (ops.containsKey(token)) {
                while ( ! stack.isEmpty() && isHigerPrec(token, stack.peek()))
                    output.push(stack.pop());
                    stack.push(token);
                }  else {
                    output.push(token);
                }
        }

        while ( ! stack.isEmpty()) 
            output.push(stack.pop());
        return reverse(output);
    }

    private static Stack<String> reverse(Stack<String> original) {
        Stack<String> reverse = new Stack<>();
        while(!original.isEmpty()) reverse.push(original.pop());
        return reverse;
   }
}

操作类:

public enum Operator {
    ADD(1), SUBTRACT(1), MULTIPLY(2), DIVIDE(2);
    final int precedence;
    Operator(int p) { precedence = p; }

    public static Map<String, Operator> ops = new HashMap<String, Operator>() {{
        put("+", Operator.ADD);
        put("-", Operator.SUBTRACT);
        put("*", Operator.MULTIPLY);
        put("/", Operator.DIVIDE);
    }};

    public static Operator fromString(String str){
        return ops.get(str);
    }
}

最后修改了你的课程:

public class RpnCalculator {
    private static Float eval(float arg1, float arg2, Operator operator) {
        switch (operator) {
            case ADD:
                return arg1 + arg2;
            case SUBTRACT:
                return arg2 - arg1;
            case MULTIPLY:
                return arg1 * arg2;
            case DIVIDE:
                return arg2 / arg1;
            default:
                throw new IllegalArgumentException("Operator not supported: " + operator);
        }
    }

    public static Float evaluateInfixExpression(String expression) {
        Stack<String> stack = ShuntingYard.postfix(expression);
        Stack<Float> result = new Stack<>();
        while(!stack.isEmpty()){
            String nextElement = stack.pop();
            if(isANumber(nextElement)){
                result.push(new Float(nextElement));
            } else {
                result.push(eval(result.pop(), result.pop(), Operator.fromString(nextElement)));
            }
        }
        return result.pop();
    }

    private static boolean isANumber(String number) {
        return number.matches("-?\\d+");
    }
}

资源:

答案 2 :(得分:1)

这是一个简单的解决方案,可以即时进行计算:

public class RpnCalculator {
    public static Float evaluateInfixExpression(String inflixExpression) {
        Stack<Float> operands = new Stack<>();
        Stack<Operator> operators = new Stack<>();

        for (String token : inflixExpression.split("\\s")) {
            if (isOperator(token)) {
                while (!operators.isEmpty() && operators.peek().hasHigherPrecedenceThan(token))
                    operands.add(eval(operands.pop(), operands.pop(), operators.pop()));
                operators.push(fromString(token));
            } else {
                operands.add(new Float(token));
            }
        }

        while (!operators.isEmpty())
            operands.add(eval(operands.pop(), operands.pop(), operators.pop()));

        return operands.pop();
    }

    private static Float eval(float arg2, float arg1, Operator operator) {
        switch (operator) {
            case ADD:
                return arg1 + arg2;
            case SUBTRACT:
                return arg1 - arg2;
            case MULTIPLY:
                return arg1 * arg2;
            case DIVIDE:
                return arg1 / arg2;
            default:
                throw new IllegalArgumentException("Operator not supported: " + operator);
        }
    }
}

Operator类:

public enum Operator {
    ADD(1), SUBTRACT(1), MULTIPLY(2), DIVIDE(2);
    final int precedence;
    Operator(int p) { precedence = p; }

    private static Map<String, Operator> ops = new HashMap<String, Operator>() {{
        put("+", Operator.ADD);
        put("-", Operator.SUBTRACT);
        put("*", Operator.MULTIPLY);
        put("/", Operator.DIVIDE);
    }};

    public static Operator fromString(String token){
        return ops.get(token);
    }

    public static boolean isOperator(String token) {
        return ops.containsKey(token);
    }

    public boolean hasHigherPrecedenceThan(String token) {
        return isOperator(token) && this.precedence >= fromString(token).precedence;
    }
}