aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/de/hysky/skyblocker/utils/Calculator.java
blob: bb6ed768f9c89a67ec663b53cf78d1d1ba48f0a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package de.hysky.skyblocker.utils;

import net.minecraft.util.Util;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Calculator {

    public enum TokenType {
        NUMBER, OPERATOR, L_PARENTHESIS, R_PARENTHESIS
    }

    public static class Token {
        public TokenType type;
        String value;
        int tokenLength;
    }

    private static final Pattern NUMBER_PATTERN = Pattern.compile("(\\d+\\.?\\d*)([kmbs]?)");
    private static final HashMap<String, Integer> magnitudeValues = Util.make(new HashMap<>(), map -> {
        map.put("s", 64);
        map.put("k", 1000);
        map.put("m", 1000000);
        map.put("b", 1000000000);
    });

    private static List<Token> lex(String input) {
        List<Token> tokens = new ArrayList<>();
        input = input.replace(" ", "").toLowerCase().replace("x", "*");
        int i = 0;
        while (i < input.length()) {
            Token token = new Token();
            switch (input.charAt(i)) {
                case '+', '-', '*', '/' -> {
                    token.type = TokenType.OPERATOR;
                    token.value = String.valueOf(input.charAt(i));
                    token.tokenLength = 1;
                }

                case '(' -> {
                    token.type = TokenType.L_PARENTHESIS;
                    token.value = String.valueOf(input.charAt(i));
                    token.tokenLength = 1;
                    //add implicit multiplication when there is a number before brackets
                    if (!tokens.isEmpty()) {
                        TokenType lastType = tokens.get(tokens.size() - 1).type;
                        if (lastType == TokenType.R_PARENTHESIS || lastType == TokenType.NUMBER) {
                            Token mutliplyToken = new Token();
                            mutliplyToken.type = TokenType.OPERATOR;
                            mutliplyToken.value = "*";
                            tokens.add(mutliplyToken);
                        }
                    }
                }

                case ')' -> {
                    token.type = TokenType.R_PARENTHESIS;
                    token.value = String.valueOf(input.charAt(i));
                    token.tokenLength = 1;
                }

                default -> {
                    token.type = TokenType.NUMBER;
                    Matcher numberMatcher = NUMBER_PATTERN.matcher(input.substring(i));
                    if (!numberMatcher.find()) {//invalid value to lex
                        throw new UnsupportedOperationException("invalid character");
                    }
                    int end = numberMatcher.end();
                    token.value = input.substring(i, i + end);
                    token.tokenLength = end;
                }
            }
            tokens.add(token);

            i += token.tokenLength;
        }

        return tokens;
    }

    /**
     * This is an implementation of the shunting yard algorithm to convert the equation to reverse polish notation
     *
     * @param tokens equation in infix notation order
     * @return equation in RPN order
     */

    private static List<Token> shunt(List<Token> tokens) {
        Deque<Token> operatorStack = new ArrayDeque<>();
        List<Token> outputQueue = new ArrayList<>();

        for (Token shuntingToken : tokens)
            switch (shuntingToken.type) {
                case NUMBER -> {
                    outputQueue.add(shuntingToken);
                }
                case OPERATOR -> {
                    int precedence = getPrecedence(shuntingToken.value);
                    while (!operatorStack.isEmpty()) {
                        Token leftToken = operatorStack.peek();
                        if (leftToken.type == TokenType.L_PARENTHESIS) {
                            break;
                        }
                        assert (leftToken.type == TokenType.OPERATOR);
                        int leftPrecedence = getPrecedence(leftToken.value);
                        if (leftPrecedence >= precedence) {
                            outputQueue.add(operatorStack.pop());
                            continue;
                        }
                        break;
                    }
                    operatorStack.push(shuntingToken);
                }
                case L_PARENTHESIS -> {
                    operatorStack.push(shuntingToken);
                }
                case R_PARENTHESIS -> {
                    while (true) {
                        if (operatorStack.isEmpty()) {
                            throw new UnsupportedOperationException("Unbalanced left parenthesis");
                        }
                        Token leftToken = operatorStack.pop();
                        if (leftToken.type == TokenType.L_PARENTHESIS) {
                            break;
                        }
                        outputQueue.add(leftToken);
                    }
                }
            }
        //empty the operator stack
        while (!operatorStack.isEmpty()) {
            Token leftToken = operatorStack.pop();
            if (leftToken.type == TokenType.L_PARENTHESIS) {
                //technically unbalanced left parenthesis error but just assume they are close after the equation and ignore them from here
                continue;
            }
            outputQueue.add(leftToken);
        }

        return outputQueue.stream().toList();
    }

    private static int getPrecedence(String operator) {
        switch (operator) {
            case "+", "-" -> {
                return 0;
            }
            case "*", "/" -> {
                return 1;
            }
            default -> throw new UnsupportedOperationException("Invalid operator");
        }
    }

    /**
     * @param tokens list of Tokens in reverse polish notation
     * @return answer to equation
     */
    private static double evaluate(List<Token> tokens) {
        Deque<Double> values = new ArrayDeque<>();
        for (Token token : tokens) {
            switch (token.type) {
                case NUMBER -> {
                    values.push(calculateValue(token.value));
                }
                case OPERATOR -> {
                    double right = values.pop();
                    double left = values.pop();
                    switch (token.value) {
                        case "+" -> {
                            values.push(left + right);
                        }
                        case "-" -> {
                            values.push(left - right);
                        }
                        case "/" -> {
                            if (right == 0) {
                                throw new UnsupportedOperationException("Can not divide by 0");
                            }
                            values.push(left / right);
                        }
                        case "*" -> {
                            values.push(left * right);
                        }
                    }
                }
                case L_PARENTHESIS, R_PARENTHESIS -> {
                    throw new UnsupportedOperationException("Equation is not in RPN");
                }
            }
        }
        if (values.isEmpty()) {
            throw new UnsupportedOperationException("Equation is empty");
        }
        return values.pop();
    }

    private static double calculateValue(String value) {
        Matcher numberMatcher = NUMBER_PATTERN.matcher(value.toLowerCase());
        if (!numberMatcher.matches()) {
            throw new UnsupportedOperationException("Invalid number");
        }
        double number = Double.parseDouble(numberMatcher.group(1));
        String magnitude = numberMatcher.group(2);

        if (!magnitude.isEmpty()) {
            if (!magnitudeValues.containsKey(magnitude)) {//its invalid if its another letter
                throw new UnsupportedOperationException("Invalid magnitude");
            }
            number *= magnitudeValues.get(magnitude);
        }

        return number;
    }

    public static double calculate(String equation) {
        return evaluate(shunt(lex(equation)));
    }
}